ts-patternライブラリのmatchでnullかundefinedのチェックをする方法 TypeScript
ts-pattern
ts-patternは型比較に使用されるライブラリです。
https://github.com/gvergnaud/ts-pattern
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