typescript 打字稿:如何映射联合数组类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49510832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: How to map over union array type?
提问by Murat Karag?z
I have the following structure:
我有以下结构:
interface Test1 {
number: number;
}
interface Test2 extends Test1 {
text: string;
}
let test: Test1[] | Test2[] = [];
test.map(obj => {}); // does not work
I am getting the error:
我收到错误:
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
无法调用类型缺少调用签名的表达式。类型 '{ (this: [Test1, Test1, Test1, Test1, Test1], callbackfn: (this: void, value: Test1, index: nu...' 没有兼容的调用签名
How can I map
over the test variable?
我怎样才能map
超过测试变量?
回答by Titian Cernicova-Dragomir
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.
问题是对于联合类型,作为函数的成员也将被类型化为联合类型,因此类型map
will(<U>(callbackfn: (value: Test1, index: number, array: Test1[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: Test2, index: number, array: Test2[]) => U)
就 typescript 而言是不可调用的。
You can either declare an array of the union of Test1
and Test2
您可以声明Test1
和的并集数组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=> {});