gpt4 book ai didi

typescript - 如何映射联合数组类型?

转载 作者:可可西里 更新时间:2023-11-01 02:18:43 26 4
gpt4 key购买 nike

我有以下结构:

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

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

我收到错误:

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

我如何映射测试变量?

最佳答案

为 4.2 编辑

map现在已经可以调用了,但是你仍然需要在它的参数上有一个显式的类型注释来让它按预期工作(类型参数不是上下文类型的)

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

Playground Link

这种情况可能会在未来的版本中得到改善,使这个答案大部分过时(参见 PR 将正确合成参数的上下文类型)

4.2 之前的原始答案

问题是对于联合类型,作为函数的成员也将被归类为联合类型,因此 map 的类型将是 (<U>(callbackfn: (value: Test1, index: number, array: Test1[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: Test2, index: number, array: Test2[]) => U)就 typescript 而言,这是不可调用的。

您可以声明Test1 的并集数组和 Test2

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

或者您可以在调用时使用类型断言:

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

关于typescript - 如何映射联合数组类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49510832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com