explaingit

gvergnaud/ts-pattern

14,990TypeScript

TLDR

TS-Pattern is a TypeScript library that adds pattern matching to JavaScript and TypeScript code.

Mindmap

A visual breakdown will appear here once this repo is fully enriched.

In plain English

TS-Pattern is a TypeScript library that adds pattern matching to JavaScript and TypeScript code. Pattern matching is a way of writing branching logic that asks not just whether a value equals something, but whether a value has a certain shape. The README explains that pattern matching is built into languages such as Python, Rust, Swift, Elixir, and Haskell, and there is a TC39 proposal to add it to JavaScript itself, but until that lands TS-Pattern provides the same idea as a small library. The main entry point is a function called match. You call match on a value, chain one or more .with calls that describe possible shapes of that value along with a handler function, and end the chain with either .exhaustive or .otherwise. The .exhaustive call uses the TypeScript type system to check that every possible case in a union type has been covered. If a case is missing, the code will not compile. This catches the common bug where someone adds a new variant to a type and forgets to update the switch statement that handles it. The library also exports a P object that contains pattern builders. Examples in the README include P.string and P.number as wildcards for those types, P.union and P.intersection for combining patterns, P.not for excluding shapes, P.when for custom predicates, and P.select for capturing parts of the matched value and passing them to the handler. Patterns can be nested inside object and array shapes, so you can ask whether a result is an ok wrapper containing data of type img with any src value, for example. The README pitches the library as small, around 2 kilobytes when bundled, and lists installation instructions for npm, pnpm, yarn, bun, and JSR. There are sandbox demos on StackBlitz showing the library used in a state reducer, in a React app that fetches GIFs, and in handlers for untyped API responses. The author also links to an online TypeScript course called Type-Level TypeScript.

Open on GitHub → Explain another repo

Generated 2026-05-21 · Model: sonnet-4-6 · Verify against the repo before relying on details.