TypeScript - 常用内置工具类型

259 阅读3分钟

TypeScript提供了多组实用程序类型来促进常见的类型转换,这些类型在全局范围内可用。

Partial

Partial<Type>构造一个类型使Type的所有属性都设置为可选。

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
interface Example {
    a: string;
    b: number;
}

type PartialExample = Partial<Example>;

/**
 * PartialExample
 * interface {
 *     a?: string | undefined;
 *     b?: number | undefined;
 * }
 */

Required

Required<Type>构造一个类型使Type的所有属性都设置为required,与Partial<Type>功能相反。

/**
 * Make all properties in T required
 */

type Required<T> = {
    [P in keyof T]-?: T[P];
};
interface Example {
    a?: string;
    b?: number;
}

type RequiredExample = Required<Example>;

/**
 * RequiredExample
 * interface {
 *     a: string;
 *     b: number;
 * }
 */

Readonly

Readonly<Type>构造一个类型使Type的所有属性都设置为readonly,这意味着构造类型的属性都是只读的,不能被修改,这对使用Object.freeze()方法的对象非常有用。

/**
 * Make all properties in T readonly
 */

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
interface Example {
    a: string;
    b: number;
}

type ReadonlyExample = Readonly<Example>;

/**
 * ReadonlyExample
 * interface {
 *     readonly a: string;
 *     readonly b: number;
 * }
 */

Record

Record<Keys, Type>构造一个对象类型,其属性键为Keys,其属性值为Type,通常可以使用Record来表示一个对象。

/**
 * Construct a type with a set of properties K of type T
 */

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

const recordExample: RecordType ={
  a: 1,
  b: "1"
}

Pick

Pick<Type, Keys>通过从Type中选择一组属性Keys来构造一个类型。

/**
 * From T, pick a set of properties whose keys are in the union K
 */

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
interface Example {
    a: string;
    b: number;
    c: symbol;
}

type PickExample = Pick<Example, "a"|"b">;

/**
 * PickExample
 * interface {
 *     a: string;
 *     b: number;
 * }
 */

Omit

Omit<Type, Keys>通过从Type中选择所有属性然后删除Keys来构造一个类型,与Pick<Type, Keys>功能相反。

/**
 * 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>>;
interface Example {
    a: string;
    b: number;
    c: symbol;
}

type OmitExample = Omit<Example, "a"|"b">;

/**
 * OmitExample
 * interface {
 *     c: symbol;
 * }
 */

Exclude

Exclude<UnionType, ExcludedMembers>通过从UnionType中排除可分配给ExcludedMembers的所有联合成员来构造类型。

/**
 * Exclude from T those types that are assignable to U
 */

type Exclude<T, U> = T extends U ? never : T;
type ExcludeExample = Exclude<"a"|"b"|"c"|"z", "a"|"b"|"d">;

/**
 * ExcludeExample
 * "c" | "z"
 */

Extract

Extract<Type, Union>通过从Type中提取所有可分配给Union的联合成员来构造一个类型,与Exclude<UnionType, ExcludedMembers>功能相反。

/**
 * Extract from T those types that are assignable to U
 */

type Extract<T, U> = T extends U ? T : never;
type ExtractExample = Extract<"a"|"b"|"c"|"z", "a"|"b"|"d">;

/**
 * ExtractExample
 * "a" | "b"
 */

NonNullable

NonNullable<Type>通过从Type中排除nullundefined来构造一个类型。

/**
 * Exclude null and undefined from T
 */

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

/**
 * NonNullableExample
 * string | number
 */

Parameters

Parameters<Type>从函数类型Type的参数中使用的类型构造元组类型。

/**
 * 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;
type FnType = (a1: number, a2: string) => void;

type ParametersExample = Parameters<FnType>;

/**
 * ParametersExample
 * [a1: number, a2: string]
 */

ConstructorParameters

ConstructorParameters<Type>从构造函数类型的类型构造元组或数组类型,其产生一个包含所有参数类型的元组类型。

/**
 * 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;
interface Example{
  fn(a: string): string;
}

interface ExampleConstructor{
    new(a: string, b: number): Example;
}

declare const Example: ExampleConstructor;

type ConstructorParametersExample = ConstructorParameters<ExampleConstructor>;

/**
 * ConstructorParametersExample
 * [a: string, b: number]
 */

ReturnType

ReturnType<Type>构造一个由函数Type的返回类型组成的类型。

/**
 * Obtain the return type of a function type
 */

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type FnType = (a1: number, a2: string) => string | number;

type ReturnTypeExample = ReturnType<FnType>;

/**
 * ReturnTypeExample
 * string | number
 */

InstanceType

InstanceType<Type>构造一个由Type中构造函数的实例类型组成的类型。

/**
 * 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;
interface Example{
  fn(a: string): string;
}

interface ExampleConstructor{
    new(a: string, b: number): Example;
}

declare const Example: ExampleConstructor;

type InstanceTypeExample = InstanceType<ExampleConstructor>;

// const a: InstanceTypeExample = new Example("a", 1); // new ExampleConstructor => Example

/**
 * InstanceTypeExample
 * Example
 */

ThisParameterType

ThisParameterType<Type>提取函数类型的this参数的类型,如果函数类型没有this参数,则为unknown

/**
 * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
 */

type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
function toHex(this: Number) {
  return this.toString(16);
}

type ThisParameterTypeExample = ThisParameterType<typeof toHex>;

/**
 * ThisParameterTypeExample
 * Number
 */