Home > Back-end >  Unable to infer property type even though it's extending from a record definition
Unable to infer property type even though it's extending from a record definition

Time:05-04

I'm confused why typescript is unable to infer that destination[destinationProperty] is a TChild when TParent extends Record<TParentProperty, TChild> which should allow it to infer that the property is of type TChild.

class Person  {
  favoriteDog: Dog | undefined;
}

class Dog  {
  name: string;
}

  function mapSingle<
    TChild extends object | undefined,
    TParent extends Record<TParentProperty, TParentPropertyType>,
    TParentProperty extends Extract<keyof TParent, string>,
    TParentPropertyType extends TChild,
  >(
    destination: TParent,
    destinationProperty: TParentProperty,
    source: TChild,
  ) {
    destination[destinationProperty] = source; // Error Line
  }

Type 'TChild' is not assignable to type 'TParent[TParentProperty]'.

Type 'object | undefined' is not assignable to type 'TParent[TParentProperty]'.

Type 'undefined' is not assignable to type 'TParent[TParentProperty]'.(2322)

Typescript Playground Example

CodePudding user response:

A bit complicating it too much here, something like this can work:

class Person  {
  favoriteDog: Dog | undefined;
}

class Dog  {
  name: string;
}

function mapSingle<
  Parent,
  ParentProp extends keyof Parent,
  Child extends Parent[ParentProp],
>(
  destination: Parent,
  destinationProperty: ParentProp,
  source: Child,
) {
  destination[destinationProperty] = source;
}

mapSingle(new Person(), "favoriteDog", new Dog())
mapSingle(new Person(), "favoriteDog", undefined)

This is the simplest version; you have one Parent, the property ParentProp, and the type of that property Child. No need for the extra generic parameters!

Playground

  • Related