实用工具类型

    Partial<T>

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

    Readonly<T>

    构造类型T,并将它所有的属性设置为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<K,T>

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

    例子

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

    Omit<T,K>

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

    例子

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

    Exclude<T,U>

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

    例子

    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<T,U>

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

    例子

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

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

    例子

    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<T>

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

    例子

    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<T>

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

    例子

    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

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

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