Monday, May 22, 2017

TypeScript–Functional magic with discriminated unions and pattern matching

If you like the Functional style of programming, you will be happy to know that TypeScript supports discriminated unions. Instead of using inheritance and creating full blown classes, you can create a simple type that can be of different ‘subtypes’, e.g. a shape can either be a circle, rectangle or square:

This is already a lot less code then when using classes, but another advantage is you can now use pattern matching over this type. The TypeScript uses control flow based type analysis and can identify the different cases in the switch and provides the correct intellisense in each case:

image

Note that I’m using another nice trick to warn me if I missed a switch statement by adding an assertNever function that throws an exception if I forgot to implement one of the cases:

image

Here is the related code:

More information at https://www.typescriptlang.org/docs/handbook/advanced-types.html

No comments: