🍰
TypeScriptのExclude<T, U>を知ろう
概要
別記事を書くにあたりExclude<T, U>を理解しようの会
Exclude<T, U>とは
ユーティリティ型の1つ。
TからUを排除したい時に使う。
参考: https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers
例えばTがstring | number、Uがnumberの場合は以下の感じ。
type Hoge = Exclude<string | number, number>; // string
const hoge: Hoge = "ほげ"; // ✅stringなのでOK
const fuga: Hoge = 0; // 🚫numberは排除されたのでNG
Tが"ほげ" | 0、Uがnumberの場合は以下の感じ。
type Hoge = Exclude<"ほげ" | 0, number>; // "ほげ"
const hoge: Hoge = "ほげ"; // ✅"ほげ"なのでOK
const fuga: Hoge = "ふが"; // 🚫"ほげ"ではないのでNG
const piyo: Hoge = 0; // 🚫number(というか0)は排除されたのでNG
never型になる条件
ちなみに、TとUが同じ場合はnever型になる。
type Hoge = Exclude<string, string>; // never
const hoge: Hoge = "ほげ"; // 🚫stringは排除されたのでNG
もうちょっと言うと、T extends Uの関係性が成り立つものはnever型になると思えばOK。
※ extendsの説明はこちら
type Hoge = Exclude<"ほげ", string>; // "ほげ"はstringの一部なので "ほげ" extends string が成り立ちnever型になる
type Fuga = Exclude<0 | 1 | 2, number>; // 0 | 1 | 2 extends number が成り立ちnever型になる
const hoge: Hoge = "ほげ"; // 🚫never型になっているのでNG
const fuga: Fuga = 0; // 🚫never型になっているのでNG
Discussion