Appearance
js 中的三元表达式
ts
interface Bird {
bird: string
}
interface Fly {
fly: string
}
interface Fish {
fish: string
}
interface Swim {
swim: string
}
type Foo<T> = T extends Bird ? Fly : Swim
type Bar = Foo<Fish>
// 条件的分发
// 先拿 Bird 去试,得到 Fly
// 再拿 Fish 去试,得到 Swim
// 最终采用它们的联合类型
// 只有联合类型会进行分发
type Baz = Foo<Bird | Fish>内置类型
Exclude
类型的排除
ts
type Exclude<T, U> = T extend U ? never : T
// 将联合类型分发,与 boolean 进行比较。never 在联合类型中会自动去除,never 没法联合。
type MyExclude = Exclude<string | number | boolean, boolean> // string | numberExtract
类型的抽离
ts
type Extract<T, U> = T extend U ? T : never
type MyExtract = Extract<string | number | boolean, boolean> // boolean非 null | undefined 检测
ts
// 源码实现
// type NonNullable<T> = T extends null | undefined ? never : T
type MyNo nNullable = NonNullable<string | number | null> // string | number