0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

ts-patternの公式を読んでいてこれの使い所なんだろうという?という機能があったので
紹介しようと思いました

そもそもts-patternとは

以下chatGPT

ts-patternは、TypeScriptで型安全なパターンマッチングを提供するライブラリです。簡潔な構文で複雑な条件分岐を実現します。

要するに、場合わけで処理を変えたい時に安全に条件分岐を扱えるようになるライブラリです。

P._ or P.any

このP._またはP.anyはなんでも通り抜ける場合わけの一種です。
otherwiseでよくない?と思いました。。。
いつでもマッチする場合?もはやts-patternいるのでしょうか。

import { match, P } from 'ts-pattern';

const input = 'hello';

const output = match(input)
  .with(P._, () => 'It will always match')
  // OR
  .with(P.any, () => 'It will always match')
  .otherwise(() => 'This string will never be used');

console.log(output);
// => 'It will always match'

さいごに

自分は用途がわからなかったので、知っている方やうまく活用している方は教えて欲しいです。
思考を張り巡らせた結果、自分の想像だと保守で致し方なく最短でこの選択肢を選ぶパターンがあるのかな?と思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?