Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring of union types in typescript

Tags:

typescript

Is there a way (similar to pattern matching from functional languages) to destructure a union type in TypeScript, i.e. some construct like:

var a: Foo | Bar = ...;

a match {
   case f: Foo => //it's a Foo!
   case b: Bar => //it's a Bar!
}

If there is no such construct - are there any technical difficulties in creating such construct?

like image 854
jfu Avatar asked Nov 20 '15 17:11

jfu


1 Answers

TypeScript understands Type Guards as a way of decomposing union types. There are several ways you can use this.

If Foo or Bar is a class, you can use instanceof:

if (a instanceof Foo) { a.doFooThing(); }

If they're interfaces, you can write a user-defined type guard:

function isFoo(f: any): f is Foo {
    // return true or false, depending....
}
if (isFoo(a)) {
   a.doFooThing();
} else {
   a.doBarThing();
}

You can also use typeof a === 'string' to test for primitive types in a union (string, number, or boolean)

like image 183
Ryan Cavanaugh Avatar answered Nov 19 '22 19:11

Ryan Cavanaugh