打字稿:如何映射联合数组类型?

打字稿:如何映射联合数组类型?

问题描述:

我有以下结构:

interface Test1 {
    number: number;
}
interface Test2 extends Test1 {
    text: string;
}

let test: Test1[] | Test2[] = [];
test.map(obj => {}); // does not work

我收到错误:


无法调用类型缺少调用签名的表达式。输入'{(this:[Test1,Test1,Test1,Test1,Test1],callbackfn :( this:void,value:Test1,index:nu ...'没有兼容的呼叫签名

Cannot invoke an expression whose type lacks a call signature. Type '{ (this: [Test1, Test1, Test1, Test1, Test1], callbackfn: (this: void, value: Test1, index: nu...' has no compatible call signatures

我如何映射而不是测试变量?

How can I map over the test variable?

问题是对于联合类型,作为函数的成员也将被输入为联合类型,因此 map 的类型将是(< U>(callbackfn :(值:Test1,index:number,array:Test1 [])=> U,thisArg?:any)=> U [])|(< ; U>(callbackfn :(值:Test2,索引:数字,数组:Test2 [])=> U)就打字稿而言,哪个不可调用。

The problem is that for union types, members which are functions will also be typed as union types, so the type of map will be (<U>(callbackfn: (value: Test1, index: number, array: Test1[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: Test2, index: number, array: Test2[]) => U) Which as far as typescript is concerned is not callable.

您可以声明 Test1 Test2 的联合数组p>

You can either declare an array of the union of Test1 and Test2

let test: (Test1 | Test2)[] = [];
test.map(obj => {}); 

或者你可以在拨打电话时使用类型断言:

Or you can use a type assertion when you make the call:

let test: Test1[] | Test2[] = [];
(test as Array<Test1|Test2>).map(o=> {});