“Pattern matching” with Typescript done right

U : never}type ShapeTypeMap = ShapeMap<Shape>// Result:type ShapeTypeMap = { Square: Square; Circle: Circle; Rectangle: Rectangle;}3.

Convert map of discriminant to its type to map of discriminant to function with its type as a parametertype ShapeTypeMap = ShapeMap<Shape>type Pattern<T> = { [K in keyof ShapeTypeMap]: (shape: ShapeTypeMap[K]) => T}// Result:type Pattern<T> = { Square: (shape: Square) => T; Circle: (shape: Circle) => T; Rectangle: (shape: Rectangle) => T;}Here you are, Typescript implementation of visitor with simple type matcher.

Visitor with pattern matching in Typescript [GIST]The funny part is type conversion (marked red).

With adding types, we gain these benefits:Compiler checks typesCompiler checks exhaustively all union optionsCompiler does auto types guardsGotchasThere is one gotcha in matcher function, where compiler is unable to resolve correct type.

I found a similar problem in this Typescript Issue.

It is ugly, but it does not affect the solution at all.

A type checking is worth a thousand tests.

Typescript playgroundPlayground · TypeScriptTry TypeScript in your browser!www.


orgCodepen playgroundConclusionThe pattern matching is nice, but an idea behind this example is, how to get part of type information from compile-time into run-time within Typescript through union discriminant property.

Thanks for reading, hope you enjoyed it and learned something new.

Comments with suggestions or corrections are very welcome.

ReferencesPattern Matching with TypeScript by Manuel AlaborFrom Gof to lambda by Mario FuscoThe Expression Problem and its solutions by Eli Bendersky.

. More details

Leave a Reply