When I use .filter to filter from array union types A and B to array of one of its sub types A, I get the following error: Type 'A' is not assignable to type 'B'.
type A = {type: "a"};
type B = {type: "b"};
type AB = A | B;
let ab: AB[] = [{type: "a"}, {type: "b"}];
let res: A[] = ab.filter(item => item.type === "a");
Is there some way to properly type this?
You can use a type assertion as other answers sugest, you can also use a custom type guard as filter
supports them
type A = {type: "a"};
type B = {type: "b"};
type AB = A | B;
let ab: AB[] = [{type: "a"}, {type: "b"}];
let res: A[] = ab.filter((item): item is A => item.type === "a");
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