Socket
Socket
Sign inDemoInstall

ts-pattern

Package Overview
Dependencies
Maintainers
1
Versions
150
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-pattern

The exhaustive Pattern Matching library for TypeScript.


Version published
Weekly downloads
1.2M
increased by5.62%
Maintainers
1
Weekly downloads
Β 
Created

What is ts-pattern?

ts-pattern is a pattern matching library for TypeScript that allows for expressive and type-safe pattern matching. It provides a way to handle complex data structures and control flow in a concise and readable manner.

What are ts-pattern's main functionalities?

Basic Pattern Matching

This feature allows you to match a value against multiple patterns and execute corresponding actions. The 'otherwise' method provides a default case.

const { match } = require('ts-pattern');

const value = 2;
const result = match(value)
  .with(1, () => 'one')
  .with(2, () => 'two')
  .with(3, () => 'three')
  .otherwise(() => 'unknown');

console.log(result); // Output: 'two'

Nested Pattern Matching

This feature allows you to match nested objects and structures, making it easier to handle complex data.

const { match } = require('ts-pattern');

const data = { type: 'user', user: { name: 'Alice', age: 30 } };
const result = match(data)
  .with({ type: 'user', user: { name: 'Alice' } }, () => 'Hello Alice')
  .with({ type: 'user', user: { age: 30 } }, () => 'User is 30 years old')
  .otherwise(() => 'Unknown user');

console.log(result); // Output: 'Hello Alice'

Guard Functions

Guard functions allow you to use custom logic to determine if a pattern matches, providing greater flexibility.

const { match, when } = require('ts-pattern');

const value = 10;
const result = match(value)
  .with(when(x => x > 5), () => 'greater than 5')
  .with(when(x => x <= 5), () => '5 or less')
  .otherwise(() => 'unknown');

console.log(result); // Output: 'greater than 5'

Other packages similar to ts-pattern

Keywords

FAQs

Package last updated on 14 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚑️ by Socket Inc