## 経緯 [[TypeScript]]では[[Rust]]における[[パターンマッチ (Rust)|パターンマッチ]]のように、switch文に分岐漏れがあっても実行時まで気づくことができない問題がある。 ## 方法 2通りの方法がある。 ### ExhausitiveErrorをつくる `ExhaustiveError`クラスを使うことでこの問題を解決する。 ```ts class ExhaustiveError extends Error { // 万が一ビルドエラーを見過ごしてもランタイムエラーで原因が分かるようなmessageに constructor(value: never, message = `Unsupported type: ${value}`) { super(message); } } type Animal = "dog" | "cat" | "owl" | "human"; function hello(animal: Animal) { switch (animal) { case "dog": console.log("bow"); break; case "cat": console.log("nyan"); break; case "owl": console.log("hoho"); break; default: throw new ExhaustiveError(animal); // Argument of type 'string' is not assignable to parameter of type 'never'.(2345) // Animalのユニオン型から"human"を消すとビルドが通る (網羅性のチェック漏れをビルド時に防げる!!) } } ``` もし`"owl"`の分岐が漏れた場合、`ExhaustiveError`の引数`animal`は`"owl"`型になり、[[never型 (TypeScript)|never型]]へのキャストは不可能なため型エラーになる。また、実行時も例外が送出される上、コード上からも意味を察しやすい。 > [!info] 参考 > - [never型 \| TypeScript入門『サバイバルTypeScript』](https://typescriptbook.jp/reference/statements/never#%E4%BE%8B%E5%A4%96%E3%81%AB%E3%82%88%E3%82%8B%E7%B6%B2%E7%BE%85%E6%80%A7%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF) > - [TypeScript: Documentation \- Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#exhaustiveness-checking) ### [[TS-Pattern]]を使う パフォーマンスをそこまで気にしなくていいケースなら[[TS-Pattern]]を使ったほうが可読性が高くなる。 <div class="link-card-v2"> <div class="link-card-v2-site"> <img class="link-card-v2-site-icon" src="https://publish-01.obsidian.md/access/35d05cd1bf5cc500e11cc8ba57daaf88/favicon-64.png" /> <span class="link-card-v2-site-name">Minerva</span> </div> <div class="link-card-v2-title"> 📒TS-Patternのユースケース </div> <div class="link-card-v2-content">TS-Patternでよく使うユースケースをまとめる。</div> <img class="link-card-v2-image" src="https://publish-01.obsidian.md/access/35d05cd1bf5cc500e11cc8ba57daaf88/Notes/attachments/typescript-recipe2.webp" /> <a data-href="📒TS-Patternのユースケース" class="internal-link"></a> </div> %%[[📒TS-Patternのユースケース]]%%