Open laclys opened 3 years ago
eg:
type ExcludeTypeKey<K> = K extends "type" ? never : K
type Test = ExcludeTypeKey<"emailAddress" | "type" | "foo">
// => "emailAddress" | "foo"
type ExcludeTypeField<A> = {[K in ExcludeTypeKey<A>]: A[K]}
type Test = ExcludeTypeField<{ type: "LOG_IN"; emailAddress: string }>
// => { emailAddress: string }
它可以在 extends 关键字右侧的类型表达式中的任何位置使用。使用它可以为出现在该位置的任何类型命名
eg:
type Unpack<A> = A extends Array<infer E> ? E : A
type Test = Unpack<Apple[]>
// => Apple
type Test = Unpack<Apple>
// => Apple
type Stairs = Unpack<Apple[] | Pear[]>
// => Apple | Pear
type Flip<T> = T extends [infer A, infer B] ? [B, A] : never
type Stairs = Flip<[Pear, Apple]>
// => [Apple, Pear]
type Union<T> = T extends [infer A, infer A] ? A : never
type Stairs = Union<[Apple, Pear]>
// => Apple | Pear
工具类
-?
来标注属性为必填的属性,-
用来清除可选性实现 Required。。+?
也是有效的,Partial可知 +? 的 +`是可以省略的eg:
eg:
eg:
type NewProps = SelectRequired<Props, 'b' | 'c'>; // { a?: string, b: string, c: string, d: string }
// 实现 type SelectRequired<T, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>
eg:
Extract<Type, Union>
type Extract<T, U> = T extends U ? T : never;
Parameters
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;