简体   繁体   English

打字稿数组映射联合

[英]Typescript array map union

I'm try to map over array that contains union of types but typescript marks my code as error, i can't figure out how i can implement this correctly, can you explain what is going on and how i can fix it ? 我正在尝试映射包含类型并集的数组,但是打字稿将我的代码标记为错误,我无法弄清楚如何正确实现这一点,您能解释发生了什么以及如何修复它吗?

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 游乐场链接

Since the array can contain either x or y you need to type guard for each of those scenarios. 由于数组可以包含xy您需要为每种情况键入guard。 For example here you could use an in type 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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM