Typescript 类型2019-09-12Θ
梳理 Typescript
的类型使用。
Typescript ECMAScript APIs 的定义。
Partial 全部指定为可选类型#
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooPartial = Partial<Foo>;
type Partial<T> = {
[P in keyof T]?: T[P];
};
部分指定为可选类型#
Omit 去掉指定字段联合 Pick 出指定字段设置为可选
type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
将 name、endpoint 标记为可选
type AccountFormType = {
name: string,
endpoint: string,
accessKey: string,
secretKey: string,
region?: string,
}
type AccountFormOptionalType = WithOptional<AccountFormType, 'name' | 'endpoint'>
Pick 选取指定的类型#
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooWithAC = Pick<Foo, 'a' | 'c'>;
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
Omit 去掉指定的类型。#
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooWithoutA = Omit<Foo, 'a' | 'c'>;
实现代码#
type Except<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
Record#
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooRecordWithString = Record<string, Foo>
type Record<K extends keyof any, T> = {
[P in K]: T;
}
Exclude 排除可分配的类型#
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooKey = keyof Foo;
type FooKeyWithoutAC = Exclude<KeyOf, 'a' | 'c'>
type Exclude<T, U> = T extends U ? never : T;
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooKey = keyof Foo;
type FooKeyWithAC = Extract<KeyOf, 'a' | 'c'>
type Extract<T, U> = T extends U ? T : never;