If I have an array filled with items of a union type and I want to find an element within the array and work with it, knowing from my find that I have narrowed the type, how do I accomplish this?
That is, if I have the following types:
interface A {
text: string;
}
interface B {
type: string;
}
type C = A|B;
and the following code
const arr: Array<C> = [....]
I want to find the first element of arr that has a type attribute.
Logically, I think this is represented by
const output = arr.find(child => {
if ('type' in child) return true;
return false
})
This seems like it should narrow the type of output to be B, but it doesn't. The compiler still seems to think that output is of type C.
The type safe way to implement the type guard in your case is
function isB(c: C): c is B {
if ('type' in c) {
return typeof c.type === 'string';
}
return false;
}
The other answer does not take into account the fact that there are valid C values that have type property that is not a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With