TypeScript Pattern Matching Library

1.0.1 · abandoned · verified Tue Apr 21

This library, `typescript-pattern-matching`, offers functional-style pattern matching capabilities for TypeScript, addressing the absence of native `match` or `case` keywords found in languages like F# or Haskell. It enables developers to implement sophisticated conditional logic by comparing data against various patterns, including value, record, wildcard, and negated patterns, with robust type inference. Version 1.0.1 is the latest release, but the project has seen no updates in over six years (last published December 2019). While it provides a basic implementation for structured pattern matching, its development has ceased, leading to a state of abandonment. More actively maintained and feature-rich alternatives have emerged in the TypeScript ecosystem. It requires TypeScript 3.7.3 or higher to function correctly.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic pattern matching on a discriminated union (`Option<T>`) and using `.otherwise()` for a default case.

import { match } from 'typescript-pattern-matching';

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

/**
 * Processes an Option type using pattern matching to extract its value
 * or handle the 'none' case.
 */
function processOption<T>(opt: Option<T>): T | string {
  const result = match(opt)
    .with({ kind: 'some' }, o => `Value is: ${o.value}`)
    .with({ kind: 'none' }, () => 'No value present.')
    .run();
  return result as T | string; // Type assertion needed for example simplicity
}

const someValue: Option<string> = { kind: 'some', value: 'hello world' };
const noneValue: Option<number> = { kind: 'none' };

console.log(processOption(someValue));
console.log(processOption(noneValue));

// Example demonstrating .otherwise() for a default case
const unknownValue = { type: 'unknown' };
const processedUnknown = match(unknownValue)
  .with({ type: 'known' }, v => `Known type: ${v.type}`)
  .otherwise(() => 'Unknown type encountered.')
  .run();

console.log(processedUnknown);

view raw JSON →