TypeScript 提供了一些工具类型,用于辅助处理常见的类型转换。这些工具类型是全局可用的。
Partial
给定一个带有任意多个属性的类型,并将它传递给 Partial,会得到一个所有属性均为可选属性的新类型。
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",});
Required
Required 做的事情与 Partial 恰好相反,给定一个带有任意多个属性的类型,将它传递给 Required,会得到一个所有属性均为必需属性的新类型。
interface Props {a?: number;b?: string;}const obj: Props = { a: 5 };const obj2: Required<Props> = { a: 5 }; // Error: Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
Readonly
顾名思义,给定一个带有任意多个属性的类型,将它传递给 Readonly,会得到一个所有属性均不可以重新赋值的新类型。
interface Todo {title: string;}const todo: Readonly<Todo> = {title: "Delete inactive users",};todo.title = "Hello"; // Error:Cannot assign to 'title' because it is a read-only property.
当表达运行时由于赋值会导致的错误时,这个工具类型非常管用,比如:为 frozen object 的属性重新赋值。
function freeze<Type>(obj: Type): Readonly<Type>;
Record
协助构建一个键值均为指定类型的对象类型,它可以用来将某个对象类型的属性映射到另一个类型。
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris; // Type: Record<CatName, CatInfo>
Pick
从目标对象类型中挑选指定的键(任意多个),构建一个新的对象类型。
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo; // Type: TodoPreview
Omit
与 Pick 相反,以目标对象类型为原型,构建一个新的对象类型,指定的键除外。
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
todo; // Type: TodoPreview
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
todoInfo; // Type: TodoInfo
Exclude
从目标类型中构建一个新的类型,不包括旧类型中能够被 ExcludeUnion 囊括的部分。
type T0 = Exclude<"a" | "b" | "c", "a">; // Type: T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // Type: T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>; // Type: T2 = string | number
Extract
与 Exclude 相反,从目标类型中构建一个新的类型,只包括旧类型中能够被 Union 囊括的部分。
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // Type: "a"
type T1 = Extract<string | number | (() => void), Function>; // Type: () => void
NonNullable
从目标类型中构建一个新的类型,但不包括其中的 null 和 undefined,与 Extract<Type, null | undefined> 相同。
type T0 = NonNullable<string | number | undefined>; // Type: string | number
type T1 = NonNullable<string[] | null | undefined>; // Type: string[]
Parameters
给定一个函数类型,根据该函数类型的参数类型,构建一个新的元组类型。特殊地,当给定的类型不是函数类型时,得到 never,当给定的类型是 any 时,得到 unknown[]。
declare function f1(arg: { a: number; b: string }): void;
type T0 = Parameters<() => string>; // Type: []
type T1 = Parameters<(s: string) => void>; // Type: [s: string]
type T2 = Parameters<<T>(arg: T) => T>; // Type: [arg: unknown]
type T3 = Parameters<typeof f1>; // Type: [arg: { a: number; b: string; }]
type T4 = Parameters<any>; // Type: unknown[]
type T5 = Parameters<never>; // Type: never
type T6 = Parameters<string>;
// Error: Type 'string' does not satisfy the constraint '(...args: any) => any'.
// Type: never
type T7 = Parameters<Function>;
// Error: Type 'Function' does not satisfy the constraint '(...args: any) => any'.
// Error: Type 'Function' provides no match for the signature '(...args: any): any'.
// Type: never
ConstructorParameters
给定一个构造函数类型,根据该构造函数类型的参数类型,构建一个新的数组或元组类型。特殊地,当给定的类型不是构造函数类型时,得到 never。
type T0 = ConstructorParameters<ErrorConstructor>; // Type: [message?: string]
type T1 = ConstructorParameters<FunctionConstructor>; // Type: string[]
type T2 = ConstructorParameters<RegExpConstructor>; // Type: [pattern: string | RegExp, flags?: string]
type T3 = ConstructorParameters<any>; // Type: unknown[]
type T4 = ConstructorParameters<Function>; // Type: never
ReturnType
给定一个函数类型,根据该函数类型的返回类型,构建一个新的类型。特殊地,当给定的类型不是函数类型时,得到的类型为 any 或者 never。
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>; // Type: string
type T1 = ReturnType<(s: string) => void>; // Type: void
type T2 = ReturnType<<T>() => T>; // Type: unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // Type: number[]
type T4 = ReturnType<typeof f1>; // Type: { a: number; b: string; }
type T5 = ReturnType<any>; // Type: any
type T6 = ReturnType<never>; // Type: never
type T7 = ReturnType<string>;
// Error: Type 'string' does not satisfy the constraint '(...args: any) => any'.
// Type: any
type T8 = ReturnType<Function>;
// Error: Type 'Function' does not satisfy the constraint '(...args: any) => any'.
// Error: Type 'Function' provides no match for the signature '(...args: any): any'.
// Type: any
InstanceType
给定一个包含构造函数的类型,返回该构造函数的实例类型。
class C {
x = 0;
y = 0;
}
type T0 = InstanceType<typeof C>; // Type: C
type T1 = InstanceType<any>; // Type: any
type T2 = InstanceType<never>; // Type: never
type T3 = InstanceType<string>;
// Error: Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
// Type: any
type T4 = InstanceType<Function>;
// Error: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
// Error: Type 'Function' provides no match for the signature 'new (...args: any): any'.
// Type: any
ThisParameterType
给定一个函数类型,提取该函数类型的 this 的类型,如果该函数没有 this 参数,则得到 unknown。
function toHex(this: Number) {
return this.toString(16);
}
function numberToString(n: ThisParameterType<typeof toHex>) {
return toHex.apply(n);
}
OmitThisParameter
给定一个函数类型,移除该函数类型的 this 参数,如果目标类型本身就没有指定 this 参数,那么返回结果就是该类型本身。如果目标类型指定了 this 参数,则返回的类型中 this 参数会被移除。如果用到重载,只有最后一条重载会被作为目标类型。
function toHex(this: Number) {
return this.toString(16);
}
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
console.log(fiveToHex());
ThisType
ThisType 并不转换目标类型,它仅仅是作为 this 的类型标记。这个功能类型需要与 noImplicitThis 一起使用。
type ObjectDescriptor<D, M> = {
data?: D;
methods?: M & ThisType<D & M>; // Type of 'this' in methods is 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 obj = makeObject({
data: { x: 0, y: 0 },
methods: {
moveBy(dx: number, dy: number) {
this.x += dx; // Strongly typed this
this.y += dy; // Strongly typed this
},
},
});
obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);
Intrinsic String Manipulation Types
TypeScript 还提供了一些辅助操作字符串的功能类型,它们包括:Uppercase<StringType>、Lowercase<StringType>、Capitalize<StringType>、Uncapitalize<StringType>,在模板字符串章节中可以看到它们的详细用法。
