Typescript: How to map over union array type?

前端 未结 1 1134
囚心锁ツ
囚心锁ツ 2020-11-27 18:07

I have the following structure:

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

let test: Test1[] | Test2[] = []         


        
相关标签:
1条回答
  • 2020-11-27 19:02

    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.

    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=> {});
    
    0 讨论(0)
提交回复
热议问题