技術ブログ

プログラミング、IT関連の記事中心

ts-patternライブラリのmatchでnullかundefinedのチェックをする方法 TypeScript

目次

ts-pattern

ts-patternは型比較に使用されるライブラリです。

github.com

null、undefinedの比較

以下のように、「P.nullish」にてnullかundefinedの場合の処理を行っています。

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

const data: string | undefined | null = "Hello";

const result = match(data)
  .with(P.nullish, () => {
    return "null or undefined";
  })
  .otherwise((h) => {
    return h;
  });

console.log(result); // Output: Hello