[英]TypeScript type assertion from mixed object list
Is it possible to find an item in an array by it's custom type?是否可以通过自定义类型在数组中找到一个项目?
type A = {
x: number;
};
type B = {
y: number;
};
type Mixed = A | B;
const list: Mixed[] = [{x:5}, {y:3}];
const a = list.find(item => 'x' in item); // <-- how to make something like this work?
This should work:这应该有效:
type A = {
x: number;
};
type B = {
y: number;
};
type Mixed = A | B;
const list: Mixed[] = [{x:5}, {y:3}];
const a = list.find(item => item.hasOwnProperty('x')) as A;
Jan isn't wrong.简没有错。 Here's a better answer, showing how to filter the mixed array into two typed lists - without the potential for a "undefined" value to be mistyped as A or B.
这是一个更好的答案,展示了如何将混合数组过滤成两个类型化的列表——而不会将“未定义”值错误地输入为 A 或 B。
type A = {
x: number;
};
type B = {
y: number;
};
type Mixed = A | B;
const list: Mixed[] = [{x:5}, {y:3}];
const isA = (candidate: Mixed): candidate is A => {
return (candidate && candidate.hasOwnProperty('x'))
}
const isB = (candidate: Mixed): candidate is B => {
return (candidate && candidate.hasOwnProperty('y'))
}
const AItems = list.filter(item => isA(item)) as A[];
const BItems = list.filter(item => isB(item)) as B[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.