tpm

typescript-pattern-matching

Pattern matching in TS with Record Patterns, Type Patterns, type inference and more

Showing:

Popularity

Downloads/wk

176

GitHub Stars

60

Maintenance

Last Commit

2yrs ago

Contributors

0

Package

Dependencies

0

Size (min+gzip)

0.6KB

License

MIT

Type Definitions

Built-In

Tree-Shakeable

No?

Categories

Readme

Pattern Matching for TypeScript

Pattern matching allows programmers to compare data with defined structures to easily pick one of the available expressions. Many languages that are designed as ‘functional programming languages’ have built-in keywords for pattern matching. Well know examples are F# (match … with) or Haskell (case … of). One language that works very well with functional programming but lacks those features is TypeScript. This library adds support pattern matching to TypeScript.

Read the article about this library for more context.

Install

yarn

yarn add typescript-pattern-matching

npm

npm -i --save typescript-pattern-matching

This library need TypeScript 3.7.3 or higher to fully function.

Features

The features of this library include:

  • Value patterns
  • Record patterns
  • Wildcard patterns
  • Good type inference based on the patterns
  • Negated patterns (including negated type inference)
  • Additional predicates (like when)

Quick Examples

type Option<a> = { kind: 'none' } | { kind: 'some', value: a }

let val: Option<string> = { kind: 'some', value: 'hello' }

match(val)
  .with({ kind: 'some' }, o => o.value)
  .run()
let blogOverviewResponse: any = /* ... */

match<any, Blog[] | Error>(blogOverviewResponse)
  .with([{Id: Number, Title: String}], r => r.map(b => ({id: b.Id, title: b.Title})))
  .with({ errorMessage: String },      r => new Error(r.errorMessage))
  .otherwise(                         () => new Error('client parse error'))
  .run()

About

This library is written by Wim Jongeneel

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial