Destroying union types in typescript

Is there a way (similar to matching with functional languages) to break the type of union in TypeScript, i.e. some construction like:

var a: Foo | Bar = ...;

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

If there is no such design, are there any technical difficulties in creating such a design?

+4
source share
1 answer

TypeScript understands Type Guards as a way to decompose union types. There are several ways to use this.

If Fooor Baris a class, you can use instanceof:

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

If these are interfaces, you can write a custom protection type:

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

typeof a === 'string' (string, number boolean)

+5

Source: https://habr.com/ru/post/1616772/


All Articles