TypeScript 类型定义
覆盖 lib
{
"dependencies": {
"@typescript/lib-dom": "npm:@types/web"
}
}
RequireOne
type RequireOne<T, K extends keyof T> = {
[X in Exclude<keyof T, K>]?: T[X];
} & {
[P in K]-?: T[P];
};
type Conf = RequireOne<Options, 'https' | 'http' | 'websocket'>;
内置
- 4.5 Awaited
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Record<K extends keyof any, T> = {
[P in K]: T;
};
type Exclude<T, U> = T extends U ? never : T;
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never;
/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
/**
* Obtain the parameters of a function type in a tuple
*/
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
/**
* Obtain the parameters of a constructor function type in a tuple
*/
type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (
...args: infer P
) => any
? P
: never;
/**
* Obtain the return type of a function type
*/
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
/**
* Obtain the return type of a constructor function type
*/
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R
? R
: any;
/**
* Convert string literal type to uppercase
*/
type Uppercase<S extends string> = intrinsic;
/**
* Convert string literal type to lowercase
*/
type Lowercase<S extends string> = intrinsic;
/**
* Convert first character of string literal type to uppercase
*/
type Capitalize<S extends string> = intrinsic;
/**
* Convert first character of string literal type to lowercase
*/
type Uncapitalize<S extends string> = intrinsic;
/**
* Marker for contextual 'this' type
*/
interface ThisType<T> {}
interface ArrayLike<T> {
readonly length: number;
readonly [n: number]: T;
}
Optional
// 部分字段 Partial
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
maybeFunction
T 需要检测是否为函数,否则直接 typeof 无法区分
// eslint-disable-next-line @typescript-eslint/ban-types
export type MaybeFunction<T, A extends any[]> = T extends Function ? (...args: A) => T : T;
export function maybeFunction<T, A extends any[]>(v: MaybeFunction<T, A>, ...args: A): T {
return typeof v === 'function' ? v(...args) : v;
}
keyof 强制为 string 类型
默认 keyof 会返回 string|number|symbol
类型
// 取 string
type StringKeys = Extract<keyof AbstractModel, string>;
// 强制 string
type Keys = keyof AbstractModel & string;
// 定义工具类型
type KeyOf<T extends object> = Extract<keyof T, string>;