日期:2021年8月4日标签:JavaScript

TypeScript中内置的泛型 #

TypeScript提供了一些比较实用的泛型类型,但是我们常常会忽略它们。本节我们将一起看看这些泛型。

泛型 #

Partial<Type> #

从一个类型,构建一个新的类型,新的类型所有的属性都来自原类型,并且新类型所有属性都是可选的。

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

type PartialTodo = Partial<Todo>;

PartialTodo类型等价于:

interface PartialTodo {
    title?: string | undefined;
    description?: string | undefined;
}

Required<Type> #

Required<Type>Partial<Type>作用相反,构建一个新的类型,新的类型所有的属性都来自原类型,但是新类型所有属性都是必须的(非可选属性)。

interface Props {
    a?: number;
    b?: string;
}
type T = Required<Props>;

T等价于:

interface T {
    a: number;
    b: string;
}

Readonly<Type> #

构建一个新的类型,新的类型所有的属性都来自原类型,新类型所有属性都是只读属性

interface Todo {
    title: string;
}

const todo: Readonly<Todo> = {
    title: "Delete inactive users",
};

// 再次给title属性赋值,会报错
todo.title = "Hello";

Record<Keys, Type> #

构建一个新的类型,该类型的属性名称来自Keys,属性值的类型是Type类型。

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" },
};

Pick<Type, Keys> #

构建一个新的类型,新类型为Type类型的子集(新类型的属性集合为Type类型属性集合的子集)。

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

type TodoPreview = Pick<Todo, "title" | "completed">;

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

Omit<Type, Keys> #

Pick<Type, Keys>类似,但是正如它的名称一样,Omit表示忽略的意思。Omit<Type, Keys>构建一个新的类型,新的类型的所有属性来自于Type,从属性中排除Keys指定的属性。

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

// TodoPreview包含title、completed、createdAt三个属性
type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
    title: "Clean room",
    completed: false,
    createdAt: 1615544252770,
};

// TodoInfo包含title、description两个属性
type TodoInfo = Omit<Todo, "completed" | "createdAt">;

const todoInfo: TodoInfo = {
    title: "Pick up kids",
    description: "Kindergarten closes at 5pm",
};

Exclude<Type, ExcludedUnion> #

构建一个新的联合类型(union),联合类型的每一项存在于Type类型中,但是不存在于ExcludedUnion类型中。TypeExcludedUnion是联合类型(union)。

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

Extract<Type, Union> #

构建一个新的联合类型(union),该类型的每一项既存在于Type中,也存在Union中。TypeUnion是联合类型(union)。

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

NonNullable<Type> #

通过从Type中排除nullundefined,构建一个新的类型。

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

Parameters<Type> #

从一个函数类型Type,构建一个由函数参数组成的元祖类型。

declare function f1(arg: { a: number; b: string }): void;
declare function f2( a: number, b: string): void;
// type T0 = []
type T0 = Parameters<() => string>;
     
// type T1 = [s: string]
type T1 = Parameters<(s: string) => void>;
     
// type T2 = [arg: unknown]
type T2 = Parameters<<T>(arg: T) => T>;

// type T3 = [arg: {
//     a: number;
//     b: string;
// }]     
type T3 = Parameters<typeof f1>;
     
// type T4 = unknown[]
type T4 = Parameters<any>;
     
// type T5 = never
type T5 = Parameters<never>;

// type T6 = [a: number, b: string]
type T6 = Parameters<typeof f2>;

ConstructorParameters<Type> #

Parameters<Type>类似,但是ConstructorParameters<Type>Type是构造函数类型。它构建一个由构造函数参数组成的元祖类型。

// type T0 = [message?: string]
type T0 = ConstructorParameters<ErrorConstructor>;

// type T1 = string[]
type T1 = ConstructorParameters<FunctionConstructor>;
     
// type T2 = [pattern: string | RegExp, flags?: string]
type T2 = ConstructorParameters<RegExpConstructor>;
     
// type T3 = unknown[]
type T3 = ConstructorParameters<any>;

ReturnType<Type> #

从函数返回值类型,构建一个新的类型。

declare function f1(): { a: number; b: string };

// type T0 = string
type T0 = ReturnType<() => string>;
     
// type T1 = void
type T1 = ReturnType<(s: string) => void>;
     
// type T2 = unknown
type T2 = ReturnType<<T>() => T>;
     
// type T3 = number[]
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;

// type T4 = {
//     a: number;
//     b: string;
// } 
type T4 = ReturnType<typeof f1>;

// type T5 = any
type T5 = ReturnType<any>;
     
// type T6 = never
type T6 = ReturnType<never>; 

InstanceType<Type> #

从实例类型构建一个新的类型。

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

// type T0 = C
type T0 = InstanceType<typeof C>;

// type T1 = any
type T1 = InstanceType<any>;

// type T2 = never
type T2 = InstanceType<never>;

ThisParameterType<Type> #

从一个函数类型中的this指针,提取类型。如果函数没有this,返回unknow

function toHex(this: Number) {
    return this.toString(16);
}

// n: Number
function numberToString(n: ThisParameterType<typeof toHex>) {
    return toHex.apply(n);
}

OmitThisParameter<Type> #

从函数类型中移除this参数,构建新的函数类型。如果Type没有显示的声明this参数,结果就等于Type

function toHex(this: Number) {
    return this.toString(16);
}

// const fiveToHex: () => string
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);

ThisType<Type> #

使用ThisType<Type>泛型类型之前,必须开启--noImplicitThis。 官方文档的说明,对我来说有些复杂,文档是这样描述的:

This utility does not return a transformed type. Instead, it serves as a marker for a contextual this type. Note that the --noImplicitThis flag must be enabled to use this utility.

官方给出的例子如下:

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

如果你也没有看懂上面的例子,可以按照我的方式去理解。当你给一个object的类型添加& ThisType<WhateverYouWantThisToBe>,那么这个object中所有方法的this参数类型都会是WhateverYouWantThisToBe。所以上面的例子中的moveBy方法的this类型为D & M

在看一个例子:

interface HelperThisValue {
    logError: (error: string) => void;
}

// helperFunctions中所有方法的this类型都为HelperThisValue
let helperFunctions: { [name: string]: Function } & ThisType<HelperThisValue> = {
    hello: function() {
        this.logError("Error: Something went wrong!"); // TypeScript successfully recognizes that "logError" is a part of "this".
        this.update(); // TS2339: Property 'update' does not exist on HelperThisValue.
    }
}

registerHelpers(helperFunctions);

附:参考资料 #

typescript handbook: Utility Types

(完)

目录