Home > Software design >  TypeScript: passing an empty array to a generic method
TypeScript: passing an empty array to a generic method

Time:12-19

Given I have this code:

const myGenericMethod = <T extends MyType1 | MyType2>(myList: T[]): T[] => {
  return myList; // simplified, my real method would return a shuffled list
};

type MyType1 = { name: 'Type1' };
type MyType2 = { name: 'Type2' };

const myList: MyType1[] | MyType2[] = [];
myGenericMethod(myList); // error!

the last line will lead to 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"'.

When I change the the myList creation to

const myList: MyType1[] | MyType2[] = [{ name: 'Type1' }];

it will work though.

My TypeScript version is 4.9.4. How can I properly support empty lists?

CodePudding user response:

I'm stupid, the answer is that my method declaration leads to a wrong union type:

const myGenericMethod = (myList: (MyType1 | MyType2)[]): (MyType1 | MyType2)[]

while I meant

const myGenericMethod = (myList: MyType1[] | MyType2[]): MyType1[] | MyType2[]

So I changed my method to

const myGenericMethod = <T extends any[]>(myList: T): T => {
  return myList;
};

There was nothing wrong with the empty array!

  • Related