实用工具类型

TypeScript 提供一些工具类型来帮助常见的类型转换。这些类型是全局可见的。

目录

Partial<Type>

构造类型Type,并将它所有的属性设置为可选的。它的返回类型表示输入类型的所有子类型。

例子

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. }
  5. function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  6. return { ...todo, ...fieldsToUpdate };
  7. }
  8. const todo1 = {
  9. title: 'organize desk',
  10. description: 'clear clutter',
  11. };
  12. const todo2 = updateTodo(todo1, {
  13. description: 'throw out trash',
  14. });

Readonly<Type>

构造类型Type,并将它所有的属性设置为readonly,也就是说构造出的类型的属性不能被再次赋值。

例子

  1. interface Todo {
  2. title: string;
  3. }
  4. const todo: Readonly<Todo> = {
  5. title: 'Delete inactive users',
  6. };
  7. todo.title = 'Hello'; // Error: cannot reassign a readonly property

这个工具可用来表示在运行时会失败的赋值表达式(比如,当尝试给冻结对象的属性再次赋值时)。

Object.freeze

  1. function freeze<T>(obj: T): Readonly<T>;

Record<Keys, Type>

构造一个类型,其属性名的类型为K,属性值的类型为T。这个工具可用来将某个类型的属性映射到另一个类型上。

例子

  1. interface PageInfo {
  2. title: string;
  3. }
  4. type Page = 'home' | 'about' | 'contact';
  5. const x: Record<Page, PageInfo> = {
  6. about: { title: 'about' },
  7. contact: { title: 'contact' },
  8. home: { title: 'home' },
  9. };

Pick<Type, Keys>

从类型Type中挑选部分属性Keys来构造类型。

例子

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. }
  6. type TodoPreview = Pick<Todo, 'title' | 'completed'>;
  7. const todo: TodoPreview = {
  8. title: 'Clean room',
  9. completed: false,
  10. };

Omit<Type, Keys>

从类型Type中获取所有属性,然后从中剔除Keys属性后构造一个类型。

例子

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. }
  6. type TodoPreview = Omit<Todo, 'description'>;
  7. const todo: TodoPreview = {
  8. title: 'Clean room',
  9. completed: false,
  10. };

Exclude<Type, ExcludedUnion>

从类型Type中剔除所有可以赋值给ExcludedUnion的属性,然后构造一个类型。

例子

  1. type T0 = Exclude<'a' | 'b' | 'c', 'a'>; // "b" | "c"
  2. type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>; // "c"
  3. type T2 = Exclude<string | number | (() => void), Function>; // string | number

Extract<Type, Union>

从类型Type中提取所有可以赋值给Union的类型,然后构造一个类型。

例子

  1. type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>; // "a"
  2. type T1 = Extract<string | number | (() => void), Function>; // () => void

NonNullable<Type>

从类型Type中剔除nullundefined,然后构造一个类型。

例子

  1. type T0 = NonNullable<string | number | undefined>; // string | number
  2. type T1 = NonNullable<string[] | null | undefined>; // string[]

Parameters<Type>

由函数类型Type的参数类型来构建出一个元组类型。

例子

  1. declare function f1(arg: { a: number; b: string }): void;
  2. type T0 = Parameters<() => string>;
  3. // []
  4. type T1 = Parameters<(s: string) => void>;
  5. // [s: string]
  6. type T2 = Parameters<<T>(arg: T) => T>;
  7. // [arg: unknown]
  8. type T3 = Parameters<typeof f1>;
  9. // [arg: { a: number; b: string; }]
  10. type T4 = Parameters<any>;
  11. // unknown[]
  12. type T5 = Parameters<never>;
  13. // never
  14. type T6 = Parameters<string>;
  15. // never
  16. // Type 'string' does not satisfy the constraint '(...args: any) => any'.
  17. type T7 = Parameters<Function>;
  18. // never
  19. // Type 'Function' does not satisfy the constraint '(...args: any) => any'.

ConstructorParameters<Type>

由构造函数类型来构建出一个元组类型或数组类型。 由构造函数类型Type的参数类型来构建出一个元组类型。(若Type不是构造函数类型,则返回never)。

例子

  1. type T0 = ConstructorParameters<ErrorConstructor>;
  2. // [message?: string | undefined]
  3. type T1 = ConstructorParameters<FunctionConstructor>;
  4. // string[]
  5. type T2 = ConstructorParameters<RegExpConstructor>;
  6. // [pattern: string | RegExp, flags?: string | undefined]
  7. type T3 = ConstructorParameters<any>;
  8. // unknown[]
  9. type T4 = ConstructorParameters<Function>;
  10. // never
  11. // Type 'Function' does not satisfy the constraint 'new (...args: any) => any'.

ReturnType<Type>

由函数类型Type的返回值类型构建一个新类型。

例子

  1. type T0 = ReturnType<() => string>; // string
  2. type T1 = ReturnType<(s: string) => void>; // void
  3. type T2 = ReturnType<(<T>() => T)>; // {}
  4. type T3 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]
  5. type T4 = ReturnType<typeof f1>; // { a: number, b: string }
  6. type T5 = ReturnType<any>; // any
  7. type T6 = ReturnType<never>; // any
  8. type T7 = ReturnType<string>; // Error
  9. type T8 = ReturnType<Function>; // Error

InstanceType<Type>

由构造函数类型Type的实例类型来构建一个新类型。

例子

  1. class C {
  2. x = 0;
  3. y = 0;
  4. }
  5. type T0 = InstanceType<typeof C>; // C
  6. type T1 = InstanceType<any>; // any
  7. type T2 = InstanceType<never>; // any
  8. type T3 = InstanceType<string>; // Error
  9. type T4 = InstanceType<Function>; // Error

Required<Type>

构建一个类型,使类型Type的所有属性为required。 与此相反的是Partial

例子

  1. interface Props {
  2. a?: number;
  3. b?: string;
  4. }
  5. const obj: Props = { a: 5 }; // OK
  6. const obj2: Required<Props> = { a: 5 }; // Error: property 'b' missing

ThisParameterType<Type>

从函数类型中提取 this 参数的类型。 若函数类型不包含 this 参数,则返回 unknown 类型。

例子

  1. function toHex(this: Number) {
  2. return this.toString(16);
  3. }
  4. function numberToString(n: ThisParameterType<typeof toHex>) {
  5. return toHex.apply(n);
  6. }

OmitThisParameter<Type>

Type类型中剔除 this 参数。 若未声明 this 参数,则结果类型为 Type 。 否则,由Type类型来构建一个不带this参数的类型。 泛型会被忽略,并且只有最后的重载签名会被采用。

例子

  1. function toHex(this: Number) {
  2. return this.toString(16);
  3. }
  4. const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
  5. console.log(fiveToHex());

ThisType<Type>

这个工具不会返回一个转换后的类型。 它做为上下文的this类型的一个标记。 注意,若想使用此类型,必须启用--noImplicitThis

例子

  1. // Compile with --noImplicitThis
  2. type ObjectDescriptor<D, M> = {
  3. data?: D;
  4. methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
  5. };
  6. function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
  7. let data: object = desc.data || {};
  8. let methods: object = desc.methods || {};
  9. return { ...data, ...methods } as D & M;
  10. }
  11. let obj = makeObject({
  12. data: { x: 0, y: 0 },
  13. methods: {
  14. moveBy(dx: number, dy: number) {
  15. this.x += dx; // Strongly typed this
  16. this.y += dy; // Strongly typed this
  17. },
  18. },
  19. });
  20. obj.x = 10;
  21. obj.y = 20;
  22. obj.moveBy(5, 5);

上面例子中,makeObject参数里的methods对象具有一个上下文类型ThisType<D & M>,因此methods对象的方法里this的类型为{ x: number, y: number } & { moveBy(dx: number, dy: number): number }

lib.d.ts里,ThisType<T>标识接口是个简单的空接口声明。除了在被识别为对象字面量的上下文类型之外,这个接口与一般的空接口没有什么不同。

操作字符串的类型

为了便于操作模版字符串字面量,TypeScript 引入了一些能够操作字符串的类型。 更多详情,请阅读模版字面量类型