メインコンテンツまでスキップ

Exclude<T, U>

Exclude<T, U>は、ユニオン型TからUで指定した型を取り除いたユニオン型を返すユーティリティ型です。

Exclude<T, U>の型引数

T

型引数Tには、ユニオン型を渡します。

U

型引数Uには、Tから取り除きたい型を渡します。

Excludeの使用例

ts
type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "E">;
ts
type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "E">;

上のPassGradeは次の型と同じになります。

ts
type PassGrade = "A" | "B" | "C" | "D";
ts
type PassGrade = "A" | "B" | "C" | "D";

Excludeの第2引数をユニオン型にすると、複数の型を取り除くこともできます。

ts
type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "D" | "E">;
type PassGrade = "A" | "B" | "C"
ts
type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "D" | "E">;
type PassGrade = "A" | "B" | "C"

Excludeの注意点

UTの部分集合である制限がありません。つまり、Tに存在しない型をUに入れてしまったり、タイポなどに気をつけなければいけません。次の例は、Pull Requestに関する型と解釈してください。

ts
type PullRequestState = "draft" | "reviewed" | "rejected";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "reviewed"
ts
type PullRequestState = "draft" | "reviewed" | "rejected";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "reviewed"

MergeableStatereviewedを意味しますが、このExcludeの使い方には2つの潜在的な問題があります。

PullRequestStateに新しい状態が追加された時

PullRequestStatetestFailedというMergeableStateに含めたくない状態を追加したとします。するとこの修正に伴ってMergeableStateの第2引数も同時に修正しないといけません。これを忘れるとtestFailedMergeableStateに含まれてしまいます。

ts
type PullRequestState = "draft" | "reviewed" | "rejected" | "testFailed";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "reviewed" | "testFailed"
ts
type PullRequestState = "draft" | "reviewed" | "rejected" | "testFailed";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "reviewed" | "testFailed"

変更した場合

PullRequestStatedraftopenに変更しました。この場合も、Excludeの第2引数の修正を忘れるとMergeableStateopenが含まれてしまいます。

ts
type PullRequestState = "open" | "reviewed" | "rejected";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "open" | "reviewed"
ts
type PullRequestState = "open" | "reviewed" | "rejected";
type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;
type MergeableState = "open" | "reviewed"