-1

Why next code doesn't work? I assumed that intersection type A & B should match either A or B.

type Id = number | string;
type EntityType<T> = T & { id: Id };

const fn = <T>(a: EntityType<T>) => { }

const fn2 = <T>() => {
    const f = fn<T>({ id: 5 }); // this line causes error
}

Link to reproduce:

https://www.typescriptlang.org/play/index.html?ssl=7&ssc=27&pln=7&pc=32#code/C4TwDgpgBAkgJlAvFAdgVwLYCMICcoA+UAzsLgJYoDmA3ALABQokUAoisOaACrgQA83AHxIo3KADIoAbyjk4ALlgIAvvQaMAxgHsUpKADMUowUIAUAQyXtOPPqYCUSEbJWMtu-UYBMJ4WadEF0YoUKgdPWBDUSNTM1l5JQBWKBUHdTcNLMYgA

egorgrushin
  • 1,185
  • 1
  • 10
  • 16
  • 1
    Does this answer your question? [Naming of TypeScript's union and intersection types](https://stackoverflow.com/questions/38855908/naming-of-typescripts-union-and-intersection-types) – E_net4 Mar 10 '20 at 08:47

1 Answers1

0

Remove the generic type from the function call:

type Id = number | string;
type EntityType<T> = T & { id: Id };

const fn = <T>(a: EntityType<T>) => { };

const fn2 = <T>() => {
    const f = fn({ id: 5 }); // this line causes error
}

Also see: could be instantiated with a different subtype of constraint 'object'

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47