Skip to Content
IsMatching

Last Updated: 3/6/2026


isMatching()

isMatching is a type guard function which checks if a pattern matches a given value.

Signature

export function isMatching<p extends Pattern<any>>( pattern: p ): (value: any) => value is InvertPattern<p>; export function isMatching<p extends Pattern<any>>( pattern: p, value: any ): value is InvertPattern<p>;

Curried Usage

isMatching is curried, which means it can be used in two ways.

With a Single Argument

Returns a type guard function:

import { isMatching, P } from 'ts-pattern'; const isBlogPost = isMatching({ type: 'blogpost', title: P.string, description: P.string, }); if (isBlogPost(value)) { // value: { type: 'blogpost', title: string, description: string } console.log(value.title); }

With Two Arguments

Directly checks if the value matches:

const blogPostPattern = { type: 'blogpost', title: P.string, description: P.string, } as const; if (isMatching(blogPostPattern, value)) { // value: { type: 'blogpost', title: string, description: string } console.log(value.title); }

Arguments

pattern: Pattern<any>

  • Required
  • The pattern a value should match.

value?: any

  • Optional
  • If provided, isMatching returns a boolean telling us whether the pattern matches the value.
  • If omitted, isMatching returns a type guard function.

Use Cases

Validating API Responses

import { isMatching, P } from 'ts-pattern'; const userPattern = { id: P.number, name: P.string, email: P.string, age: P.optional(P.number), }; type User = P.infer<typeof userPattern>; async function fetchUser(id: number): Promise<User | null> { const response = await fetch(`/api/users/${id}`); const data: unknown = await response.json(); if (isMatching(userPattern, data)) { return data; // data is now typed as User } return null; }

Array Filtering

const isValidPost = isMatching({ id: P.number, title: P.string, published: true, }); const posts: unknown[] = await fetchPosts(); const validPosts = posts.filter(isValidPost); // validPosts: { id: number, title: string, published: true }[]

Runtime Type Checking

function processData(data: unknown) { if (isMatching({ type: 'user', data: P.array(P.string) }, data)) { // data: { type: 'user', data: string[] } data.data.forEach((item) => console.log(item)); } else if (isMatching({ type: 'error', message: P.string }, data)) { // data: { type: 'error', message: string } console.error(data.message); } }

Benefits

  • Type safety: Automatically narrows types based on patterns
  • Reusable: Create named type guards for common patterns
  • Composable: Works with all TS-Pattern features
  • Runtime validation: Validate data at runtime with type inference