Skip to Content
Index

Last Updated: 3/6/2026


Patterns

A pattern is a description of the expected shape of your input value.

Patterns can be regular JavaScript values ("some string", 10, true, …), data structures (objects, arrays, …), wildcards (P._, P.string, P.number, …), or special matcher functions (P.not, P.when, P.select, …).

All wildcards and matcher functions can be imported either as Pattern or as P from the ts-pattern module.

import { match, Pattern } from 'ts-pattern'; const toString = (value: unknown): string => match(value) .with(Pattern.string, (str) => str) .with(Pattern.number, (num) => num.toFixed(2)) .with(Pattern.boolean, (bool) => `${bool}`) .otherwise(() => 'Unknown');

Or:

import { match, P } from 'ts-pattern'; const toString = (value: unknown): string => match(value) .with(P.string, (str) => str) .with(P.number, (num) => num.toFixed(2)) .with(P.boolean, (bool) => `${bool}`) .otherwise(() => 'Unknown');

Pattern Types