ts-pattern

ts-pattern

TypeScript高效模式匹配库 支持智能类型推断

ts-pattern是一个TypeScript模式匹配库,支持对各种数据结构进行exhaustive模式匹配。它提供智能类型推断、类型安全性和穷尽性检查。该库API灵活,包含多种模式和通配符,支持属性选择,且体积仅2kB左右。ts-pattern可用于简化复杂条件判断,提高代码可读性和安全性。

TS-PatternTypeScript模式匹配类型推断代码分支Github开源项目
<h1 align="center">TS-Pattern</h1> <p align="center"> The exhaustive Pattern Matching library for <a href="https://github.com/microsoft/TypeScript">TypeScript</a> with smart type inference. </p> <p align="center"> <a href="https://www.npmjs.com/package/ts-pattern"> <img src="https://img.shields.io/npm/dm/ts-pattern.svg" alt="downloads" height="18"> </a> <a href="https://www.npmjs.com/package/ts-pattern"> <img src="https://img.shields.io/npm/v/ts-pattern.svg" alt="npm version" height="18"> </a> <a href="https://github.com/gvergnaud/ts-pattern"> <img src="https://img.shields.io/npm/l/ts-pattern.svg" alt="MIT license" height="18"> </a> </p>
import { match, P } from 'ts-pattern'; type Data = | { type: 'text'; content: string } | { type: 'img'; src: string }; type Result = | { type: 'ok'; data: Data } | { type: 'error'; error: Error }; const result: Result = ...; const html = match(result) .with({ type: 'error' }, () => <p>Oups! An error occured</p>) .with({ type: 'ok', data: { type: 'text' } }, (res) => <p>{res.data.content}</p>) .with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => <img src={src} />) .exhaustive();

About

Write better and safer conditions. Pattern matching lets you express complex conditions in a single, compact expression. Your code becomes shorter and more readable. Exhaustiveness checking ensures you haven’t forgotten any possible case.

ts-pattern

<p align="center"><i>Animation by <a target="_blank" href="https://twitter.com/nicoespeon/status/1644342570389061634?s=20">@nicoespeon</a></i></p>

Features

What is Pattern Matching?

Pattern Matching is a code-branching technique coming from functional programming languages that's more powerful and often less verbose than imperative alternatives (if/else/switch statements), especially for complex conditions.

Pattern Matching is implemented in Haskell, Rust, Swift, Elixir, and many other languages. There is a tc39 proposal to add Pattern Matching to EcmaScript, but it is still in stage 1 and isn't likely to land before several years. Luckily, pattern matching can be implemented in userland. ts-pattern Provides a typesafe pattern matching implementation that you can start using today.

Read the introduction blog post: Bringing Pattern Matching to TypeScript 🎨 Introducing TS-Pattern

Installation

Via npm

npm install ts-pattern

Via yarn

yarn add ts-pattern

Via pnpm

pnpm add ts-pattern

Via Bun

bun add ts-pattern

Compatibility with different TypeScript versions

TS-Pattern assumes that Strict Mode is enabled in your tsconfig.json file.

ts-patternTypeScript v5+TypeScript v4.5+TypeScript v4.2+
v5.x (Docs) (Migration Guide)
v4.x (Docs) (Migration Guide)
v3.x (Docs)
  • ✅ Full support
  • ❌ Not supported

Want to learn how to build awesome, strongly-typed libraries?

Check out 👉 Type-Level TypeScript, my online course teaching how to take full advantage of the most advanced features of TypeScript. You will learn everything there is to know to build awesome libraries with great developer experiences and become a real TypeScript expert in the process!

Documentation

Sandbox examples

Getting Started

As an example, let's create a state reducer for a frontend application that fetches some data.

Example: a state reducer with ts-pattern

Our application can be in four different states: idle, loading, success and error. Depending on which state we are in, some events can occur. Here are all the possible types of event our application can respond to: fetch, success, error and cancel.

I use the word event but you can replace it with action if you are used to Redux's terminology.

type State = | { status: 'idle' } | { status: 'loading'; startTime: number } | { status: 'success'; data: string } | { status: 'error'; error: Error }; type Event = | { type: 'fetch' } | { type: 'success'; data: string } | { type: 'error'; error: Error } | { type: 'cancel' };

Even though our application can handle 4 events, only a subset of these events make sense for each given state. For instance we can only cancel a request if we are currently in the loading state. To avoid unwanted state changes that could lead to bugs, we want our state reducer function to branch on both the state and the event, and return a new state.

This is a case where match really shines. Instead of writing nested switch statements, we can use pattern matching to simultaneously check the state and the event object:

<!-- prettier-ignore -->
import { match, P } from 'ts-pattern'; const reducer = (state: State, event: Event) => match([state, event]) .returnType<State>() .with( [{ status: 'loading' }, { type: 'success' }], ([_, event]) => ({ status: 'success', data: event.data }) ) .with( [{ status: 'loading' }, { type: 'error', error: P.select() }], (error) => ({ status: 'error', error }) ) .with( [{ status: P.not('loading') }, { type: 'fetch' }], () => ({ status: 'loading', startTime: Date.now() }) ) .with( [ { status: 'loading', startTime: P.when((t) => t + 2000 < Date.now()), }, { type: 'cancel' }, ], () => ({ status: 'idle' }) ) .with(P._, () => state) .exhaustive();

There's a lot going on, so let's go through this code bit by bit:

match(value)

match takes a value and returns a builder on which you can add your pattern matching cases.

<!-- prettier-ignore -->
match([state, event])

It's also possible to specify the input and output type explicitly with match<Input, Output>(...), but this is usually unnecessary, as TS-Pattern is able to infer them.

.returnType<OutputType>()

.returnType is an optional method that you can call if you want to force all following code-branches to return a value of a specific type. It takes a single type parameter, provided between <AngleBrackets>.

.returnType<State>()

Here, we use this method to make sure all branches return a valid State object.

.with(pattern, handler)

Then we add a first with clause:

.with( [{ status: 'loading' }, { type: 'success' }], ([state, event]) => ({ // `state` is inferred as { status: 'loading' } // `event` is inferred as { type: 'success', data: string } status: 'success', data: event.data, }) )

The first argument is the pattern: the shape of value you expect for this branch.

The second argument is the handler function: the code branch that will be called if the input value matches the pattern.

The handler function takes the input value as first parameter with its type narrowed down to what the pattern matches.

P.select(name?)

In the second with clause, we use the P.select function:

.with( [ { status: 'loading' }, { type: 'error', error: P.select() } ], (error) => ({ status: 'error', error }) )

P.select() lets you extract a piece of your input value and inject it into your handler. It is pretty useful when pattern matching on deep data structures because it avoids the hassle of destructuring your input in your handler.

Since we didn't pass any name to P.select(), It will inject the event.error property as first argument to the handler function. Note that you can still access the full input value with its type narrowed by your pattern as second argument of the handler function:

.with( [ { status: 'loading' }, { type: 'error', error: P.select() } ], (error, stateAndEvent) => { // error: Error // stateAndEvent: [{ status: 'loading' }, { type: 'error', error: Error }] } )

In a pattern, we can only have a single anonymous selection. If you need to select more properties on your input data structure, you will need to give them names:

.with( [ { status: 'success', data: P.select('prevData') }, { type: 'error', error: P.select('err') } ], ({ prevData, err }) => { // Do something with (prevData: string) and (err: Error). } )

Each named selection will be injected inside a selections object, passed as first argument to the handler function. Names can be any strings.

P.not(pattern)

If you need to match on everything but a specific value, you can use a P.not(<pattern>) pattern. it's a function taking a pattern and returning its opposite:

.with( [{ status: P.not('loading') }, { type: 'fetch' }], () => ({ status: 'loading' }) )

P.when() and guard functions

Sometimes, we need to make sure our input value respects a condition that can't be expressed by a pattern. For example, imagine you need to check that a number is positive. In these cases, we can use guard functions: functions taking a value and returning a boolean.

With TS-Pattern, there are two ways to use a guard function:

  • use P.when(<guard function>) inside one of your patterns
  • pass it as second parameter to .with(...)

using P.when(predicate)

.with( [ { status: 'loading', startTime: P.when((t) => t + 2000 < Date.now()), }, { type: 'cancel' }, ], () => ({ status: 'idle' }) )

Passing a guard function to .with(...)

.with optionally accepts a guard function as second parameter, between the pattern and the handler callback:

.with( [{ status: 'loading' }, { type: 'cancel' }], ([state, event]) => state.startTime + 2000 < Date.now(), () => ({ status: 'idle' }) )

This pattern will only match if the guard function returns true.

the P._ wildcard

P._ will match any value. You can use it either at the top level, or within another pattern.

.with(P._, () => state) // You could also use it inside another pattern: .with([P._, P._], () => state) // at any level: .with([P._, { type: P._ }], () => state)

.exhaustive(), .otherwise() and .run()

.exhaustive();

.exhaustive() executes the pattern matching expression, and returns the result. It also enables exhaustiveness checking, making sure we don't forget any possible case in our input value. This extra type safety is very nice because forgetting a case is an easy mistake to make, especially in an evolving code-base.

Note that exhaustive pattern matching is optional. It comes with the trade-off of having slightly longer compilation times because the type checker has more work to do.

Alternatively,

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成热门AI工具AI图像AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具使用教程AI营销产品酷表ChatExcelAI智能客服
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

数据安全AI助手热门AI工具AI辅助写作AI论文工具论文写作智能生成大纲
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

热门AI工具AI办公办公工具智能排版AI生成PPT博思AIPPT海量精品模板AI创作
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多