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

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

问题描述

我有以下结构:

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

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

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

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