TS-Pattern

5.9.0 · active · verified Sun Apr 19

TS-Pattern is an exhaustive pattern matching library for TypeScript, providing a typesafe and highly ergonomic API to handle complex conditional logic. It is currently at version 5.9.0 and receives regular updates, often including new pattern types, performance improvements, and type inference enhancements. Key differentiators include its extensive support for various data structures (objects, arrays, tuples, sets, maps, primitives), robust type inference, and crucial exhaustiveness checking, ensuring all possible cases are handled at compile-time. It aims to provide a user-land implementation of pattern matching, similar to those found in functional languages, anticipating a future TC39 proposal, while maintaining a tiny bundle footprint of around 2kB.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates pattern matching on a discriminated union `UserProfile` using `match` and `P.select` for extracting values, `P.array` for matching array types, and `exhaustive` to ensure all cases are handled, returning a personalized dashboard message.

import { match, P } from 'ts-pattern';

type UserRole = 'admin' | 'editor' | 'viewer';

type UserProfile = 
  | { role: 'admin'; permissions: string[]; department: string }
  | { role: 'editor'; projects: string[]; lastLogin: Date }
  | { role: 'viewer'; lastViewed: string; theme: 'dark' | 'light' };

const getUserDashboardContent = (user: UserProfile): string => {
  return match(user)
    .with({ role: 'admin', department: P.select('dept') }, ({ dept }) => 
      `Welcome Admin! You manage the ${dept} department.`
    )
    .with({ role: 'editor', projects: P.array(P.string) }, (editor) => 
      `Hello Editor! Your active projects are: ${editor.projects.join(', ')}.`
    )
    .with({ role: 'viewer', theme: 'dark' }, () => 
      `Viewer mode: Enjoy your dark theme.`
    )
    .with({ role: 'viewer', theme: 'light' }, () => 
      `Viewer mode: Enjoy your light theme.`
    )
    .exhaustive();
};

const adminUser: UserProfile = { role: 'admin', permissions: ['full'], department: 'IT' };
const editorUser: UserProfile = { role: 'editor', projects: ['Project Alpha', 'Project Beta'], lastLogin: new Date() };
const viewerUserDark: UserProfile = { role: 'viewer', lastViewed: 'docs', theme: 'dark' };

console.log(getUserDashboardContent(adminUser));
console.log(getUserDashboardContent(editorUser));
console.log(getUserDashboardContent(viewerUserDark));

view raw JSON →