实用工具类型


介绍

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

目录

Partial<T>

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

例子

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

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

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

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

Readonly<T>

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

Js中文网 – ts中文手册,JavaScript 教程, www.javascriptC.com,typescript 中文文档
一个帮助开发者成长的社区,你想要的,在这里都能找到

例子

interface Todo {
    title: string;
}

const todo: Readonly = {
    title: 'Delete inactive users',
};

todo.title = 'Hello'; // Error: cannot reassign a readonly property

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

Object.freeze

function freeze(obj: T): Readonly;

Record<K,T>

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

例子

interface PageInfo {
    title: string;
}

type Page = 'home' | 'about' | 'contact';

const x: Record = {
    about: { title: 'about' },
    contact: { title: 'contact' },
    home: { title: 'home' },
};

Pick<T,K>

从类型T中挑选部分属性K来构造类型。

例子

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

type TodoPreview = Pick;

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

Omit<T,K>

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

例子

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

type TodoPreview = Omit;

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

Exclude<T,U>

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

例子

type T0 = Exclude<"a" | "b" | "c", "a">;  // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;  // "c"
type T2 = Exclude void), Function>;  // string | number

Extract<T,U>

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

Js中文网 – ts中文手册,JavaScript 教程, www.javascriptC.com,typescript 中文文档
一个帮助开发者成长的社区,你想要的,在这里都能找到

例子

type T0 = Extract<"a" | "b" | "c", "a" | "f">;  // "a"
type T1 = Extract void), Function>;  // () => void

NonNullable<T>

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

例子

type T0 = NonNullable;  // string | number
type T1 = NonNullable;  // string[]

ReturnType<T>

由函数类型T的返回值类型构造一个类型。

例子

type T0 = ReturnType<() => string>;  // string
type T1 = ReturnType<(s: string) => void>;  // void
type T2 = ReturnType<(() => T)>;  // {}
type T3 = ReturnType<(() => T)>;  // number[]
type T4 = ReturnType;  // { a: number, b: string }
type T5 = ReturnType;  // any
type T6 = ReturnType;  // any
type T7 = ReturnType;  // Error
type T8 = ReturnType;  // Error

InstanceType<T>

由构造函数类型T的实例类型构造一个类型。

例子

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

type T0 = InstanceType;  // C
type T1 = InstanceType;  // any
type T2 = InstanceType;  // any
type T3 = InstanceType;  // Error
type T4 = InstanceType;  // Error

Required<T>

构造一个类型,使类型T的所有属性为required

例子

interface Props {
    a?: number;
    b?: string;
};

const obj: Props = { a: 5 }; // OK

const obj2: Required = { a: 5 }; // Error: property 'b' missing

ThisType<T>

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

例子

// Compile with --noImplicitThis

type ObjectDescriptor = {
    data?: D;
    methods?: M & ThisType;  // Type of 'this' in methods is D & M
}

function makeObject(desc: ObjectDescriptor): 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);

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

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

看完两件小事

如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:

  1. 关注我们的 画漫画的程序员 GitHub仓库,让我们成为长期关系
  2. 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
  3. 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程

JS中文网是中国领先的新一代开发者社区和专业的技术媒体,一个帮助开发者成长的社区,目前已经覆盖和服务了超过 300 万开发者,你每天都可以在这里找到技术世界的头条内容。欢迎热爱技术的你一起加入交流与学习,JS中文网的使命是帮助开发者用代码改变世界