Skip to Content
P When

Last Updated: 3/6/2026


P.when Patterns

P.when lets you define your own logic to check if the pattern should match or not.

If the predicate function given to when returns a truthy value, then the pattern will match for this input.

Note that you can narrow down the type of your input by providing a Type Guard functionย  to P.when.

import { match, P } from 'ts-pattern'; type Input = { score: number }; const output = match({ score: 10 }) .with( { score: P.when((score): score is 5 => score === 5), }, (input) => '๐Ÿ˜' // input is inferred as { score: 5 } ) .with({ score: P.when((score) => score < 5) }, () => '๐Ÿ˜ž') .otherwise(() => '๐Ÿ™‚'); console.log(output); // => '๐Ÿ™‚'

Type Guard Functions

If you pass a type guardย  function to P.when, TS-Pattern will use its return type to narrow the input.

const isString = (x: unknown): x is string => typeof x === 'string'; const isNumber = (x: unknown): x is number => typeof x === 'number'; const fn = (input: { id: number | string }) => match(input) .with({ id: P.when(isString) }, (narrowed /* : { id: string } */) => 'yes') .with({ id: P.when(isNumber) }, (narrowed /* : { id: number } */) => 'yes') .exhaustive();