npm ts-pattern 5.8.0
v5.8.0

one month ago

TS-Pattern v5.8.0 Release Notes

New Feature: .narrow() Method for Deep Type Narrowing

.narrow() gives you fine-grained control over type narrowing of deeply nested union types during pattern matching.

What is .narrow()?

The .narrow() method allows you to explicitly narrow the input type to exclude all values that have been handled by previous patterns. This is especially useful when working with:

  • Deeply nested union types
  • Nullable properties at any nesting level
  • Complex type structures where you need precise type information

When to Use .narrow()

By default, TS-Pattern automatically narrows top-level union types as you pattern match. However, for deeply nested types, this narrowing doesn't happen automatically to maintain optimal TypeScript performance. The .narrow() method gives you explicit control over when to perform this more computationally expensive operation.

Example Usage

type Input = { user: { role: 'admin' | 'editor' | 'viewer' } };

declare const input: Input;

const result = match(input)
  .with({ user: { role: 'admin' } }, handleAdmin)
  .narrow() // Explicitly narrow remaining cases
  .with({ user: { role: 'editor' } }, handleEditor)
  .narrow() // Narrow again if needed
  .otherwise((remaining) => {
    // remaining.user.role is now precisely 'viewer'
    handleViewer(remaining);
  });

Key Benefits

  1. Precise Type Control: Get exactly the type information you need when you need it
  2. Type-checking Performance: Only pay the type-checking cost when necessary

Additional Improvements

  • Added a new release script to streamline our publishing process
  • Updated dependencies and package configurations

Full Changelog: v5.7.1...v5.8.0

PRs

  • feat: .narrow() method & typechecking perf improvement by @gvergnaud in #261

Don't miss a new ts-pattern release

NewReleases is sending notifications on new releases.