Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript 类型记录 #5

Open
wangxingkang opened this issue Mar 18, 2020 · 1 comment
Open

TypeScript 类型记录 #5

wangxingkang opened this issue Mar 18, 2020 · 1 comment

Comments

@wangxingkang
Copy link
Owner

wangxingkang commented Mar 18, 2020

内置类型

Exclude<T, U>,Omit<T, K>

移除 T 中的 U 属性

type Exclude<T, U> = T extends U ? never : T;
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

举例

// 'a' | 'd'
type A = Exclude<'a'|'b'|'c'|'d' ,'b'|'c'|'e' >  

interface Info {
  id: string;
  name: string;
  email: string;
}

type NonCoreInfo = Omit<Info, 'name' | 'email'>
/**
 * { id: string; }
 */

Extract

Exclude 的反操作,取 T,U两者的交集属性

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

例子

// 'b'|'c'
type A = Extract<'a'|'b'|'c'|'d' ,'b'|'c'|'e' >  

Partial

将类型 T 的所有属性标记为可选属性

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

Required

与 Partial 相反,Required 将类型 T 的所有属性标记为必选属性

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

Readonly

将所有属性标记为 readonly, 即不能修改

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

Pick<T, K>

从 T 中过滤出属性 K

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

Record<K, T>

标记对象的 key value类型

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

举例

interface UserInfo {
  name: string;
  age: number;
}

//  定义 学号(key)-用户信息(value) 的对象
const userMap: Record<number, AccountInfo> = {
  10001: {
    name: 'xx',
    age: 'xxxxx',
  },
  ...    
}

const user: Record<'name'|'email', string> = {
    name: '', 
    email: ''
}

NonNullable

排除类型 T 的 null | undefined 属性

type NonNullable<T> = T extends null | undefined ? never : T;

Parameters

获取一个函数的所有参数类型

type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

ConstructorParameters

类似于 Parameters, ConstructorParameters 获取一个类的构造函数参数

type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;

ReturnType

获取函数类型 T 的返回类型

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

InstanceType

获取一个类的返回类型

type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
@wangxingkang
Copy link
Owner Author

wangxingkang commented Mar 19, 2020

一些类型定义库

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant