Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
ts-pattern
Advanced tools
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.
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'
match-ts is another TypeScript pattern matching library. It offers similar functionality to ts-pattern but with a different API design. It focuses on providing a more functional programming style.
typescript-pattern-matching is a library that provides pattern matching capabilities for TypeScript. It is similar to ts-pattern but may have different performance characteristics and API design choices.
fp-ts is a library for functional programming in TypeScript. While it is not solely focused on pattern matching, it provides utilities for handling data structures and control flow in a functional style, which can be used to achieve similar outcomes.
A complete pattern matching library for typescript.
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: string }
| { status: 'error'; error: Error };
type Event =
| { type: 'fetch' }
| { type: 'success'; data: string }
| { type: 'error'; error: Error }
| { type: 'cancel' };
import { match, __, not } from 'ts-pattern';
const initState: State = {
status: 'idle',
};
const reducer = (state: State, event: Event): State =>
// Sometimes you want to match on two values at once.
// Here we pattern match both on the state and the event
// and return a new state.
match<[State, Event], State>([state, event])
// the first argument is the pattern : the shape of the value
// you expect for this branch.
.with([{ status: 'loading' }, { type: 'success' }], ([, event]) => ({
status: 'success',
data: event.data,
}))
// The second argument is the function that will be called if
// the data matches the given pattern.
// The type of the data structure is narrowed down to
// what is permitted by the pattern.
.with([{ status: 'loading' }, { type: 'error' }], ([, event]) => ({
status: 'error',
error: event.error,
}))
.with([{ status: 'loading' }, { type: 'cancel' }], () => initState)
// if you need to exclude a value, you can use
// a `not` pattern. it's a function taking a pattern
// and returning its opposite.
.with([{ status: not('loading') }, { type: 'fetch' }], () => ({
status: 'loading',
}))
// `__` is a wildcard, it will match any value.
// You can use it at the top level, or inside a data structure.
.with(__, () => state)
// You can also use `otherwise`, which is equivalent to `with(__)`.
.otherwise(() => state)
// `run` execute the match close, and returns the value
.run();
type Input = { type: string } | string;
match<Input, 'ok'>({ type: 'hello' })
.with(__, (value) => 'ok') // value: Input
.with(__.string, (value) => 'ok') // value: string
.with(
when((value) => true),
(value) => 'ok' // value: Input
)
.with(not('hello'), (value) => 'ok') // value: Input
.with(not(__.string), (value) => 'ok') // value: { type: string }
.with(not(when(() => true)), (value) => 'ok') // value: Input
.with({ type: __ }, (value) => 'ok') // value: { type: string }
.with({ type: __.string }, (value) => 'ok') // value: { type: string }
.with({ type: when(() => true) }, (value) => 'ok') // value: { type: string }
.with({ type: not('hello' as 'hello') }, (value) => 'ok') // value: { type: string }
.with({ type: not(__.string) }, (value) => 'ok') // value: { type: string }
.with({ type: not(when(() => true)) }, (value) => 'ok') // value: { type: string }
.with(not({ type: when(() => true) }), (value) => 'ok') // value: string
.with(not({ type: __.string }), (value) => 'ok') // value: string
.run();
FAQs
The exhaustive Pattern Matching library for TypeScript.
The npm package ts-pattern receives a total of 989,302 weekly downloads. As such, ts-pattern popularity was classified as popular.
We found that ts-pattern demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.