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?
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)
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