Exclude<T, U>
Exclude<T, U>
は、ユニオン型T
からU
で指定した型を取り除いたユニオン型を返すユーティリティ型です。
#
Exclude<T, U>の型引数#
T型引数T
には、ユニオン型を渡します。
#
U型引数U
には、T
から取り除きたい型を渡します。
#
Excludeの使用例typescript
type Grade = "A" | "B" | "C" | "D" | "E";type PassGrade = Exclude<Grade, "E">;
typescript
type Grade = "A" | "B" | "C" | "D" | "E";type PassGrade = Exclude<Grade, "E">;
上のPassGradeは次の型と同じになります。
typescript
type PassGrade = "A" | "B" | "C" | "D";
typescript
type PassGrade = "A" | "B" | "C" | "D";
Exclude
の第2引数をユニオン型にすると、複数の型を取り除くこともできます。
typescript
type Grade = "A" | "B" | "C" | "D" | "E";type PassGrade = Exclude<Grade, "D" | "E">;//=> "A" | "B" | "C"
typescript
type Grade = "A" | "B" | "C" | "D" | "E";type PassGrade = Exclude<Grade, "D" | "E">;//=> "A" | "B" | "C"
#
Excludeの注意点U
はT
の部分集合である制限がありません。つまり、T
に存在しない型をU
に入れてしまったり、タイポなどに気をつけなければいけません。次の例は、Pull Requestに関する型と解釈してください。
typescript
type PullRequestState = "draft" | "reviewed" | "rejected";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "reviewed"
typescript
type PullRequestState = "draft" | "reviewed" | "rejected";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "reviewed"
MergeableState
はreviewed
を意味しますが、このExclude
の使い方には2つの潜在的な問題があります。
PullRequestState
に新しい状態が追加された時#
PullRequestState
にtestFailed
というMergeableState
に含めたくない状態を追加したとします。するとこの修正に伴ってMergeableState
の第2引数も同時に修正しないといけません。これを忘れるとtestFailed
はMergeableState
に含まれてしまいます。
typescript
type PullRequestState = "draft" | "reviewed" | "rejected" | "testFailed";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "reviewed" | "testFailed"
typescript
type PullRequestState = "draft" | "reviewed" | "rejected" | "testFailed";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "reviewed" | "testFailed"
#
変更した場合PullRequestState
のdraft
をopen
に変更しました。この場合も、Exclude
の第2引数の修正を忘れるとMergeableState
にopen
が含まれてしまいます。
typescript
type PullRequestState = "open" | "reviewed" | "rejected";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "open" | "reviewed"
typescript
type PullRequestState = "open" | "reviewed" | "rejected";type MergeableState = Exclude<PullRequestState, "draft" | "rejected">;//=> "open" | "reviewed"