如何映射联合数组类型? [英] How to map over union array type?

查看:27
本文介绍了如何映射联合数组类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

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

如何映射测试变量?

推荐答案

Edit for 4.2

map 现在已经可以调用了,但是您仍然需要在其参数上进行显式类型注释才能使其按预期工作(类型参数没有上下文类型)

map has become callable now, but you still need an explicit type annotation on its argument to get it to work as expected (the type parameter is no contextually typed)

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

游乐场链接

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

This situation is likely to improve in future versions making this answer mostly obsolete (see PR that will correctly synthesize contextual types for parameters)

4.2 之前的原始答案

问题是,对于联合类型,作为函数的成员也会被类型化为联合类型,所以 map 的类型将是 (<U>(callbackfn: (value: Test1, 索引: number, array: Test1[]) => U, thisArg?: any) => U[]) |(<U>(callbackfn: (value: Test2, index: number, array: 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.

你可以声明一个Test1Test2

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=> {});

这篇关于如何映射联合数组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆