Skip to Content
ReturnType

Last Updated: 3/6/2026


.returnType()

The .returnType<SomeType>() method allows you to control the return type of all of your branches of code. It accepts a single type parameter that will be used as the return type of your match expression.

Signature

function returnType<TOutputOverride>(): Match<TInput, TOutputOverride>;

Type Arguments

TOutputOverride

The type that your match expression will return. All branches must return values assignable to it.

Example

import { match, P } from 'ts-pattern'; type State = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: string }; const handleState = (state: State) => match(state) .returnType<State>() // Force all branches to return State .with({ status: 'idle' }, () => ({ status: 'loading' })) .with({ status: 'loading' }, () => ({ status: 'success', data: 'done' })) .with({ status: 'success' }, (s) => s) .exhaustive();

Type Checking

All code branches must return values assignable to the specified type:

match(input) .returnType<string>() .with('hello', () => 'greeting') // ✅ OK .with(42, () => 'number') // ✅ OK .with(true, () => 123) // ❌ Error: number is not assignable to string .otherwise(() => 'default');

When to Use

Use .returnType() when:

  1. You want explicit type control: Ensure all branches return a specific type
  2. Working with complex types: Make sure transformations preserve type structure
  3. State machines: Guarantee state transitions return valid states
  4. Refactoring safety: Catch type errors early when changing return types

Optional Usage

Note that .returnType() is optional. TypeScript can usually infer the return type from your handler functions:

// TypeScript infers return type as string const result = match(value) .with('a', () => 'letter a') .with('b', () => 'letter b') .otherwise(() => 'other');