Xen_mar
Xen_mar

Reputation: 9702

Constrained generic type return value needs to relate to argument

I'm relatively new to TypeScript and I've stumbled on a concept that I struggle to understand. Example - Playground link:

interface Base {
  one: number;
  two: number;
}

type ExampleFunction = <T extends Base>(args: T) => {[key in keyof T]: T[key]};

const exampleFunction: ExampleFunction = (arg) => {
  return { <-- this object throws an error
    one: arg.one,
    two: arg.two,
  }
}

As far as I understand it, I contain the generic to an object with two key-value-pairs. However, if I try to return an object with these properties, the types don't match. I'd love to understand why.

Upvotes: 0

Views: 21

Answers (1)

Nikita Ivanov
Nikita Ivanov

Reputation: 856

When a type T extends your interface, it means that it probably adds some more properties to a base type, or narrows its existing properties. Here are examples of interfaces that conform the extends Base condition:

type T1 = {one: number; two: number; three: number};
type T2 = {one: 1; two: 2};

If you apply exampleFunction to arg of type T1, it will not return an object of type you have declared: property three will be missing. For this particular case you may be looking for some construction like return {...arg} – it will keep all properties in place, so Typescript will be satisfied with it.

Upvotes: 1

Related Questions