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,

编辑推荐精选

Refly.AI

Refly.AI

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

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

酷表ChatExcel

酷表ChatExcel

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

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

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
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工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

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

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

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

下拉加载更多