Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering from union type to subtype

Tags:

typescript

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?

like image 1000
Petr Hurtak Avatar asked Oct 20 '25 21:10

Petr Hurtak


1 Answers

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");
like image 117
Titian Cernicova-Dragomir Avatar answered Oct 22 '25 11:10

Titian Cernicova-Dragomir