首页 > 解决方案 > 映射 2 种不同类型的 TypeScript 数组,其条件为仅存在于一种类型上的属性?

问题描述

我有类型AB. 是和Items的数组。此代码有效:AB

type A = {
    foo: string;
    isB: false;
}

type B = {
    bar: string;
    isB: true;
}

type Items = (A | B)[];


const myItems: Items = [
    {
        foo: 'First string';
        isB: false;
    },
    {
        bar: 'Second string';
        isB: true;
    }
]


myItems.map((item, index)=>{
    if(item.isA) {
        return <ComponentA key={index} {...item} />
    }
    return <ComponentB key={index} {...item} />
})

我试图简化它,所以该isB属性只存在于B类型上。

type A = {
    foo: string;
}

type B = {
    bar: string;
    isB: true;
}

type Items = (A | B)[];


const myItems: Items = [
    {
        foo: 'First string';
    },
    {
        bar: 'Second string';
        isB: true;
    }
]


myItems.map((item, index)=>{
    if(item.isA) {
        return <ComponentA key={index} {...item} />
    }
    return <ComponentB key={index} {...item} />
})

但是我收到一个错误:

  类型“A”上不存在属性“isRest”。

标签: reactjstypescript

解决方案


您可以使用in运算符将​​联合缩小到特定类型:

myItems.map((item, index)=>{
    if('isB' in item) {
        return <ComponentB key={index} {...item} />
    }
    return <ComponentA key={index} {...item} />
})

游乐场


推荐阅读