For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/match/P.md.

P

The pattern primitives namespace. Builds patterns that match by type, structure, or predicate.

Source: ts-pattern

Most of P is re-exported from ts-pattern. Massaman extends it with P.ok and P.err for matching Result values—see P.ok and P.err below.

import { P } from 'massaman/match'
// or:  import { P } from 'massaman'

Primitives

PatternMatches
P.stringany string
P.numberany number
P.booleanany boolean
P.bigintany bigint
P.symbolany symbol
P.nullishnull or undefined
P.any / P._anything
P.array(pattern)array where every item matches pattern
P.union(a, b, …)matches if any sub-pattern matches
P.intersection(a, b, …)matches if every sub-pattern matches
P.not(pattern)matches if pattern does NOT match
P.optional(pattern)matches undefined or the pattern
P.when(predicate)matches when predicate(value) is truthy — bridge to massaman predicates
P.select()captures the matched value for the handler
P.select('name', pattern)captures a sub-value by name
P.ok(pattern?)matches an Ok Result, optionally constraining its value — massaman extension
P.err(pattern?)matches an Err Result, optionally constraining its error — massaman extension

P.ok

Matches the Ok variant of a Result<T>. With no argument it is equivalent to { ok: true }; with an argument it applies that pattern to value.

import { match, P, attempt } from 'massaman'

match(attempt(() => JSON.parse(raw)))
  .with(P.ok(), ({ value }) => render(value))
  .with(P.err(), ({ error }) => log(error))
  .exhaustive()

Inside the P.ok() arm, the matched value is narrowed to Ok<T>value is typed as T, error is null.

Pass a pattern to constrain the contained value:

match(result)
  .with(P.ok({ name: 'jane' }), () => 'jane!')
  .with(P.ok(), ({ value }) => `got ${value.name}`)
  .with(P.err(), ({ error }) => `err: ${error.message}`)
  .exhaustive()

P.err

Matches the Err variant of a Result<T>. With no argument it is equivalent to { ok: false }; with an argument it applies that pattern to error.

Inside the P.err() arm, the matched value is narrowed to Errerror is Error, value is null.

Examples

import { match, P } from 'massaman'

// Discriminate on shape
match(input)
  .with({ kind: 'user', name: P.string }, ({ name }) => `hello ${name}`)
  .with({ kind: 'guest' }, () => 'hello stranger')
  .otherwise(() => 'unknown')
import { match, P } from 'massaman'
import { isEmpty } from 'massaman/predicate'

// Bridge to a massaman predicate via P.when
match(arr)
  .with(P.when(isEmpty), () => 'empty')
  .with(P.array(P.number), (nums) => `${nums.length} numbers`)
  .otherwise(() => 'something else')

See also