「JavaScript」カテゴリーのロゴ

【TypeScript】Union型に含まれる値かどうかを判定する

やりたいこと

type HogeType = "xx" | "xxx" | "xxxx";

const isHoge = (arg: any): arg is HogeType => {
  // argがHogeに含まれるか判定したい
};

とある値がUnion型に含まれるかどうかを判定したい。

解決法

+ const hoges = ["xx", "xxx", "xxxx"] as const;
- type HogeType = "xx" | "xxx" | "xxxx";
+ type HogeType = (typeof hoges)[number];

 const isHoge = (arg: any): arg is HogeType => {
-   // argがHogeに含まれるか判定したい
+   return hoges.some((hoge) => hoge === arg);
 };
  1. 配列からUnion型を定義する
  2. ユーザー定義型ガードの関数内で、その配列に含まれるかどうかを判定する