Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active August 23, 2022 01:24
Show Gist options
  • Save yano3nora/24457f8f821a2c56903c9c7cf7f6fb82 to your computer and use it in GitHub Desktop.
Save yano3nora/24457f8f821a2c56903c9c7cf7f6fb82 to your computer and use it in GitHub Desktop.
[js: ts-pattern] Pattern matching library for TypeScript. #js #ts

Overview

github.com/gvergnaud/ts-pattern

$ npm i ts-pattern
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 = /* ... */

return 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() // コンパイル時にパターン網羅性をチェック
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment