实用工具类型

    Partial<Type>

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

    Readonly<Type>

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

    例子

    1. interface Todo {
    2. title: string;
    3. }
    4. title: 'Delete inactive users',
    5. };
    6. 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. type TodoPreview = Pick<Todo, 'title' | 'completed'>;
    6. const todo: TodoPreview = {
    7. title: 'Clean room',
    8. completed: false,
    9. };

    Omit<Type, Keys>

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

    例子

    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)。

    ReturnType<Type>

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

    例子

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

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

    例子

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

    Required<Type>

    例子

    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 参数,则返回 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 参数,则结果类型为 Type 。 否则,由Type类型来构建一个不带this参数的类型。 泛型会被忽略,并且只有最后的重载签名会被采用。

    ThisType<Type>

    这个工具不会返回一个转换后的类型。 它做为上下文的类型的一个标记。 注意,若想使用此类型,必须启用--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.moveBy(5, 5);

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

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

    操作字符串的类型

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