typescript 工具泛型

Partial

1
2
3
4
5
6
7
8
9
10
11
12
13
interface A {
name: string;
age: number
};

type Partial<T> = { [K in keyof T]?: T[K] };

type PartialTest = Partial<A>

// type PartialTest = {
// name?: string;
// age?: number;
// }

Required

1
type Required<T> = { [K in keyof T]-?: T[K] };

Mutable

1
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

Readonly

1
type Readonly<T> = { readonly [K in keyof T]: T[K] };

Record

1
type Record<K extends keyof any, T> = { [U in  K]: T};

Pick

1
type Pick<T, K extends keyof T> = { [P in K]: T[P]}

Exclude

1
2
3
type Exclude<T, U> = T extends U ? never : T;

type T1 = Exclude<1 | 2, 1 | 3> // -> 2

Extract

1
2
3
type Extract<T, U> = T extends U ? T : never;

type T2 = Extract<1 | 2, 1 | 3> // -> 1

Omit

1
2
3
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;

type Foo = Omit<{name: string, age: number}, 'name'> // -> { age: number }

ReturnType

1
type ReturnType<T> = T extends (...args: any) => infer P ? P : any;
Author: Rick
Link: https://rcrick.github.io/2020/04/30/typescript-工具泛型/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶