Skip to content

TypeScript does not have any pattern matching functionality built in. This article shows several ways how you can replicate the core of a simple pattern matcher using a few simple structures and functions within TypeScript. Resulting code will have improved maintainability and better runtime type safety when done right.

License

Notifications You must be signed in to change notification settings

swissmanu/pattern-matching-with-typescript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Pattern Matching with TypeScript

Pattern matching is a fundamental and powerful building block to many functional programming languages like Haskell or Scala.

(In case you have never heard anything about pattern matching, think about it like a type safe switch statement on steroids.)

TypeScript (and with that, JavaScript) has no pattern matching functionality built in.

Boolean Pattern

Following code introduces an interface containing cases to handle possible values of the boolean type. Each case is a function which will return a T.

interface BooleanPattern<T> { True: () => T, False: () => T }

The BooleanPattern allows us to describe specific behaviours for each possible case.

Following matchBoolean function takes such behaviour description and returns a matcher. function which then will execute the matching case by

function matchBoolean<T>(p: BooleanPattern): (b: boolean) => T { return (b: boolean) => { if (b) { return p.True(); } return p.False(); } }

This could be used:

const loggedIn: boolean = await isUserLoggedIn(); const result = matchBoolean({ True: () => 'User is logged in', False: () => 'User is logged out' })(loggedIn);

About

TypeScript does not have any pattern matching functionality built in. This article shows several ways how you can replicate the core of a simple pattern matcher using a few simple structures and functions within TypeScript. Resulting code will have improved maintainability and better runtime type safety when done right.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •