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?

はじめに

ts-patternP.notを完全に理解しよう

P.not はどんなときに使うのか

任意のインプットに対し、複数の型定義を許容する場合
特定の型定義に対して異なるアウトプットを表現する関数を定義することができる。

* 以下は公式の例
booleanまたはnumberの型定義を持ったInputに対して、
InputbooleanでないときはInputでやってきたnumberを返す。
Inputbooleanのときはtrueであれば, falseのときはを返す。

以下の例では
数値の型に返す関数だが、関数の型定義を行っていないためそれ以外の値を返すことも可能。

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

type Input = boolean | number;

const toNumber = (input: Input) =>
  match(input)
    .with(P.not(P.boolean), (n) => n) // n: number
    .with(true, () => 1)
    .with(false, () => 0)
    .exhaustive();

console.log(toNumber(2));
// => 2
console.log(toNumber(true));
// => 1

さいごに

自分はts-patternを基本enumのインプットに対してしか使う場面がなかったので、
出会うことがなかったが、型定義を超越して扱えるということがわかったので、
typeScriptの意義を履き違えないようにしながら上手く活用していきたい。

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?