Skip to main content

Utility Types

TypeScript提供了一些实用类型,可以用于操作和转换现有的类型,这些实用类型在全局范围内都可用。

Partial<Type>

构造一个类型,并将Type的所有属性设置为可选。该实用类型将返回一个表示给定类型的所有子集的类型。

interface Todo {
title: string;
description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
title: 'organize desk',
description: 'clear clutter',
}

const todo2 = updateTodo(todo1, {
description: 'throw out trash',
})

// MyPartial
type MyPartial<T> = {
[P in keyof T]?: T[P] | undefined;
}

Required<Type>

构造一个类型,并将Type中的所有属性设置为必选,与Partial相反。

interface Props {
x?: number;
y?: number;
}

type RequiredProps = Required<Props>;

const obj1 = { x: 5 };
// Property 'y' is missing in type '{ x: number; }'
// but required in type 'Required<Props>'.
const obj2: RequiredProps = {
x: 5
};

// MyRequired
type MyRequired<T> = {
[p in keyof T]-?: T[p];
}

Readonly<Type>

构造一个类型,并将Type中的所有属性设置为只读,意味着新构造类型的属性均不能被重新赋值。

interface Todo {
title: string;
description: string;
}

const todo: Readonly<Todo> = {
title: 'Delete inactive users',
description: 'clear out inactive users',
}
// Cannot assign to 'description' because it is a read-only property.
todo.description = 'hello'

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

此实用类型对于表示在运行时(即尝试重新分配冻结对象的属性时)失败的赋值表达式非常有用。

function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys, Type>

构造一个对象类型,其属性键为Keys,属性值的类型为Type。此实用类型可用于将一种类型的属性映射到另一种类型。

interface AnimalInfo {
age: number;
breed: string;
}

type CatName = 'cat' | 'dog';

const animal: Record<CatName, AnimalInfo> = {
cat: { age: 5, breed: 'persian' },
dog: { age: 10, breed: 'german' },
}

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

Pick<Type, Keys>

Type中选取属性Keys(字符串文字或字符串文字的并集)集来构造新类型。

interface Todo {
title: string;
description: string;
completed: boolean;
}

type TodoPreview = Pick<Todo, 'title' | 'completed'>;

const todo: TodoPreview = {
title: 'Clean room',
completed: false,
}

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

Exclude<UnionType, ExcludedMembers>

UnionType中排除所有可分配给ExcludedMembers的联合成员来构造类型。

// type TO = "b" | "c"
type TO = Exclude<'a' | 'b' | 'c', 'a'>;

// type T1 = string | number
type T1 = Exclude<string | number | (() => void), Function>

type ShapeOptions = { kind: 'circle', radius: number } | { kind: 'square', sideLength: number };

// type T3 = {
// kind: 'square';
// sideLength: number;
// }
type T3 = Exclude<ShapeOptions, { kind: 'circle' }>;

// MyExclude
type MyExclude<T, U> = T extends U ? never : T;
/**
type A = 'a' extends 'a' ? never : 'a';
type B = 'b' extends 'a' ? never : 'b';
type Res = never | 'b'
*/
type Res1 = MyExclude<'a' | 'b', 'a'>

Omit<Type, Keys>

Type中选取所有属性,然后删除Keys(字符串文字或字符串文字的并集)来构造类型,与Pick正好相反。

interface Todo {
title: string;
description: string;
completed: boolean;
}

type TodoPreview = Omit<Todo, 'description'>;

const todo: TodoPreview = {
title: 'Clean room',
completed: false,
}

type MyOmit<T, K extends keyof T> = {
[S in MyExclude<keyof T, K>]: T[S]
}

Extract<Type, Union>

Type中提取可分配给Union的所有联合成员来构造类型。

// type TO = "a"
type TO = Extract<'a' | 'b' | 'c', 'a'>;

// type T1 = () => void
type T1 = Extract<string | number | (() => void), Function>

type ShapeOptions = { kind: 'circle', radius: number } | { kind: 'square', sideLength: number };

// type T3 = {
// kind: 'circle';
// radius: number;
// }
type T3 = Extract<ShapeOptions, { kind: 'circle' }>;

// MyExtract
type MyExtract<T, U> = T extends U ? T : never;
/**
type A = 'a' extends 'a' ? 'a' : never;
type B = 'b' extends 'a' ? 'b' : never;
type Res = 'a' | never
*/
type Res1 = MyExtract<'a' | 'b', 'a'>

NonNullable<Type>

Type中排除nullundefined来构造类型。

// type T0 = string | number
type T0 = NonNullable<string | number | undefined>;

// type T1 = string[]
type T1 = NonNullable<string[] | null | undefined>;

Parameters<Type>

根据函数类型Type的参数中使用的类型构造元组类型,这里的Type是一个函数类型。

declare function f11(arg: { a: number, b: string }): void;

// type T0 = []
type T0 = Parameters<() => string>;

// type T1 = [s: string]
type T1 = Parameters<(s: string) => void>;

// type T2 = [arg: unknown]
type T2 = Parameters<<T>(arg: T) => T>;

// type T3 = [arg: { a: number, b: string; }]
type T3 = Parameters<typeof f11>;

// type T4 = unknown[]
type T4 = Parameters<any>;

// type T5 = never
type T5 = Parameters<never>;

// Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T6 = Parameters<string>;

ConstructorParameters<Type>

从构造函数类型的类型构造元组或数组类型。 它生成一个包含所有参数类型的元组类型(如果Type不是函数,则永远不会生成该类型)。

class Base {
constructor(a: number, b: number) { }
}

// type T0 = [a: number, b: number]
type T0 = ConstructorParameters<typeof Base>;

// type T1 = [pattern: string | RegExp, flags?: string | undefined]
type T1 = ConstructorParameters<RegExpConstructor>;

// type T2 = unknown[]
type T2 = ConstructorParameters<any>;

ReturnType<Type>

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

// type T0 = string
type T0 = ReturnType<() => string>;

// type T1 = void
type T1 = ReturnType<(s: string) => void>;

// type T2 = unknown
type T2 = ReturnType<<T>() => T>;

// type T3 = number[]
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;

// type T4 = any
type T4 = ReturnType<any>;

// type T5 = never
type T5 = ReturnType<never>;

InstanceType<Type>

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

class C {
x = 0;
y = 0;
}

type T = InstanceType<typeof C>;
type T1 = InstanceType<any>;
type T2 = InstanceType<never>;

ThisParameterType<Type>

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

function toHex(this: Number) {
return this.toString(16);
}

function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}

numberToString(123);

OmitThisParameter<Type>

Type中删除this参数。 如果Type没有显式声明此参数,则结果Type。 否则,将从 Type创建一个不带this参数的新函数类型。 泛型被删除,只有最后一个重载签名被传播到新的函数类型中。

type MyFunction = (this: string, num: number) => void;

type UpdatedFunction = OmitThisParameter<MyFunction>;

const myFunction: UpdatedFunction = function (num) {
console.log(num);
};

myFunction(42);

ThisType<Type>

此工具类型不返回转换后的类型。 相反,它充当上下文this类型的标记。需启用noImplicitThis 标志才能使用此工具类型。

type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>;
}

function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
let data: object = desc.data || {};
let methods: object = desc.methods || {};
return { ...data, ...methods } as D & M;
}

let objs = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx;
this.y += dy;
}
}
})

在上面的例子中,作为 makeObject 参数的 methods 对象具有一个上下文类型,其中包括 ThisType<D & M>,因此 methods 对象内部方法中的 this 的类型为 { x: number, y: number } & { moveBy(dx: number, dy: number): void }。请注意,methods 属性的类型同时是推断的目标和 methods 内部 this 类型的来源。这意味着在 methods 对象内部的方法中,可以使用联合类型 **{** x: number, y: number } & { moveBy(dx: number, dy: number): void } 来表示 this 的类型。

Awaited<Type>

这种类型旨在对异步函数中的awaitPromise上的.then()方法等操作进行建模。具体来说,它们递归地解开 Promises的方式,可理解为指定了Promiseresolve后返回数据的类型。

// type PA = string
type PA = Awaited<Promise<string>>;
// type PB = number
type PB = Awaited<Promise<Promise<number>>>;
// type PC = null | boolean
type PC = Awaited<null | Promise<Promise<Promise<boolean>>>>;

async function fetchData(): Promise<string> {
return "Data has been fetched!";
}

type Result = Awaited<ReturnType<typeof fetchData>>;

async function main() {
const result: Result = await fetchData();
console.log(result);
}

main();

Uppercase<StringType>

将字符串类型中的所有字符转换为大写。

type MyString = 'hello' | 'world';
// type MyUppercaseString = "HELLO" | "WORLD"
type MyUppercaseString = Uppercase<MyString>;

Lowercase<StringType>

将字符串类型中的所有字符转换为小写。

type MyString = 'HELLO' | 'WORLD';
// type MyUppercaseString = "hello" | "world"
type MyUppercaseString = Lowercase<MyString>;

Capitalize<StringType>

将字符串类型中的所有字符首字母转为大写。

type MyString = 'hello' | 'world';
// type MyUppercaseString = "Hello" | "World"
type MyUppercaseString = Capitalize<MyString>;

Uncapitalize<StringType>

将字符串类型中的所有字符首字母转为小写。