Although C# remains an object-oriented programming language, it has incorporated more and more functional techniques over the years. One of this techniques is ‘pattern matching’.
On the Microsoft Learn website, it is explained like this:
Pattern matching is a technique where you test an expression to determine if it has certain characteristics.
Not so sexy right? In fact it is rather boring described like this. That is because pattern matching is not something fancy new. It is here to simplify complex if-else statements into more compact and readable code. Pattern matching does not aim at writing code that cannot be written without. Its only purpose is to have more concise and elegant code.
There are multiple supported pattern types; constant patterns, declaration patterns, relational patterns, and so on…
In this post I want to talk about a specific pattern; the type pattern.
The type pattern in itself is quite simple, it checks the runtime type of an expression. Here is a simple example in C#:
A typical use case where I apply this is inside a CQRS or Actor model based system where a CommandHandler or Actor could handle multiple message types:
TypeScript also supports pattern matching, but you have to use a workaround when you want to use a type pattern. You cannot check the type itself but what you can do is add a type property on your object and combine this with a discriminated union:
This type object can then be used inside your switch statement. The Typescript compiler will give you intellisense and detects the different types and their properties: