'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?
Solution 1:[1]
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.
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[];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aadmaa |
