Consider the following code snippet:
const myGenericMethod = <T extends MyType1 | MyType2>(myList: T[]): T[] => {
return myList; // simplified, actual method would return a shuffled list
};
type MyType1 = { name: 'Type1' };
type MyType2 = { name: 'Type2' };
const myList: MyType1[] | MyType2[] = [];
myGenericMethod(myList); // encountered an error!
Running the last line triggers a type error:
TS2345: Argument of type 'MyType1[] | MyType2[]' is not assignable to parameter of type 'MyType1[]'.
Type 'MyType2[]' is not assignable to type 'MyType1[]'.
Type 'MyType2' is not assignable to type 'MyType1'.
Types of property 'name' are incompatible.
Type '"Type2"' is not assignable to type '"Type1"'.
If I modify the creation of myList
to be
const myList: MyType1[] | MyType2[] = [{ name: 'Type1' }];
the error disappears and it works perfectly.
Using TypeScript version 4.9.4
, how can I handle empty lists properly?