TypeScript:将空数组传递给泛型方法

oxf4rvwz  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(169)

假设我有这样的代码:

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!

最后一行将导致类型错误:

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"'.

当我将myList创建更改为

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

但它会起作用。
我的TypeScript版本是4.9.4。我如何正确支持空列表?

9gm1akwq

9gm1akwq1#

我很笨,答案是我的方法声明导致了一个错误的联合类型:

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

我是说

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

所以我改变了方法

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

空数组没有问题!

相关问题