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",
};
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;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
Exclude<Type, ExcludedUnion>
构建一个新的联合类型(union),联合类型的每一项存在于Type 类型中,但是不存在于ExcludedUnion 类型中。Type 和ExcludedUnion 是联合类型(union)。
type T0 = Exclude<"a" | "b" | "c", "a">;
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
type T2 = Exclude<string | number | (() => void), Function>;
Extract<Type, Union>
构建一个新的联合类型(union),该类型的每一项既存在于Type 中,也存在Union 中。Type 和Union 是联合类型(union)。
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T1 = Extract<string | number | (() => void), Function>;
NonNullable<Type>
通过从Type中排除null 和undefined ,构建一个新的类型。
type T0 = NonNullable<string | number | undefined>;
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 = Parameters<() => string>;
type T1 = Parameters<(s: string) => void>;
type T2 = Parameters<<T>(arg: T) => T>;
type T3 = Parameters<typeof f1>;
type T4 = Parameters<any>;
type T5 = Parameters<never>;
type T6 = Parameters<typeof f2>;
ConstructorParameters<Type>
与Parameters<Type> 类似,但是ConstructorParameters<Type> 的Type 是构造函数类型。它构建一个由构造函数参数组成的元祖类型。
type T0 = ConstructorParameters<ErrorConstructor>;
type T1 = ConstructorParameters<FunctionConstructor>;
type T2 = ConstructorParameters<RegExpConstructor>;
type T3 = ConstructorParameters<any>;
ReturnType<Type>
从函数返回值类型,构建一个新的类型。
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
type T1 = ReturnType<(s: string) => void>;
type T2 = ReturnType<<T>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T4 = ReturnType<typeof f1>;
type T5 = ReturnType<any>;
type T6 = ReturnType<never>;
InstanceType<Type>
从实例类型构建一个新的类型。
class C {
x = 0;
y = 0;
}
type T0 = InstanceType<typeof C>;
type T1 = InstanceType<any>;
type T2 = InstanceType<never>;
ThisParameterType<Type>
从一个函数类型中的this 指针,提取类型。如果函数没有this ,返回unknow 。
function toHex(this: Number) {
return this.toString(16);
}
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: 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>;
};
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;
this.y += dy;
},
},
});
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;
}
let helperFunctions: { [name: string]: Function } & ThisType<HelperThisValue> = {
hello: function() {
this.logError("Error: Something went wrong!");
this.update();
}
}
registerHelpers(helperFunctions);
附:参考资料
typescript handbook: Utility Types
(完)
|