Skip to Content
Tuples Arrays

Last Updated: 3/6/2026


Tuple and Array Patterns

Tuples (arrays)

In TypeScript, Tuples  are arrays with a fixed number of elements that can be of different types. You can pattern-match on tuples using a tuple pattern. A tuple pattern will match if the input value is an array of the same length, and each item matches the corresponding sub-pattern.

import { match, P } from 'ts-pattern'; type Input = | [number, '+', number] | [number, '-', number] | [number, '*', number] | ['-', number]; const input = [3, '*', 4] as Input; const output = match(input) .with([P._, '+', P._], ([x, , y]) => x + y) .with([P._, '-', P._], ([x, , y]) => x - y) .with([P._, '*', P._], ([x, , y]) => x * y) .with(['-', P._], ([, x]) => -x) .exhaustive(); console.log(output); // => 12

P.array patterns

To match on arrays of unknown size, you can use P.array(subpattern). It takes a sub-pattern, and will match if all elements in the input array match this sub-pattern.

import { match, P } from 'ts-pattern'; type Input = { title: string; content: string }[]; let input: Input = [ { title: 'Hello world!', content: 'This is a very interesting content' }, { title: 'Bonjour!', content: 'This is a very interesting content too' }, ]; const output = match(input) .with( P.array({ title: P.string, content: P.string }), (posts) => 'a list of posts!' ) .otherwise(() => 'something else'); console.log(output); // => 'a list of posts!'

Matching variadic tuples with P.array

In TypeScript, Variadic Tuple Types  are array types created with the ... spread operator, like [string, ...string[]], [number, ...boolean[], string] etc. You can match against variadic tuple types using array literals containing ...P.array(subpattern):

import { match, P } from 'ts-pattern'; type Input = (number | string)[]; declare const input: Input; const output = match(input) // P.array's parameter is optional .with([P.string, ...P.array()], (input) => input) // input: [string, ...(number | string)[]] .with(['print', ...P.array(P.string)], (input) => input) // input: ['print', ...string[]] // you can put patterns on either side of `...P.array()`: .with([...P.array(P.string), 'end'], (input) => input) // input: [...string[], 'end'] .with(['start', ...P.array(P.string), 'end'], (input) => input) // input: ['start', ...string[], 'end'] .otherwise((input) => input);