打字稿数组映射联合

时间:2018-10-31 14:23:15

标签: typescript

我正在尝试映射包含类型并集的数组,但是打字稿将我的代码标记为错误,我无法弄清楚如何正确实现它,可以解释发生了什么以及如何修复它?

interface x {
    name: string;
}

interface y {
    value: string;
}

const arr: (x | y)[] = [{ name: '1' }, { value: '2' }];
arr.map(item => {
    console.log(item.name); // error here
})

Playground link

1 个答案:

答案 0 :(得分:0)

由于数组可以包含xy,因此您需要为每种情况键入guard。例如,在这里您可以使用in类型防护:

interface x {
    name: string;
}

interface y {
    value: string;
}

const arr: (x | y)[] = [{ name: '1' }, { value: '2' }];
arr.map(item => {
    if ('name' in item) {
        console.log(item.name);
    }
});
相关问题