返回
Typescript 类型编程,Omit、Exclude 以及 ThisParameterType 类型的使用
前端
2023-10-05 12:12:28
在上一篇文章中,我们介绍了如何使用 TypeScript 中的 Pick 和 Exclude 类型来创建新的类型。在本文中,我们将继续探讨其他几个有用的 TypeScript 类型:Omit、Exclude 和 ThisParameterType。
Omit 类型
Omit 类型用于从一个类型中移除指定的属性,从而创建一个新的类型。其语法如下:
type Omit<T, K> = {
[P in keyof T]: P extends K ? never : T[P];
};
其中:
T
是要从中移除属性的类型。K
是要从T
中移除的属性的类型。
例如,我们可以使用 Omit 类型从 Person
类型中移除 age
和 city
属性,创建一个新的 PartialPerson
类型:
type Person = {
name: string;
age: number;
city: string;
};
type PartialPerson = Omit<Person, "age" | "city">;
现在,PartialPerson
类型只包含 name
属性:
const person: PartialPerson = {
name: "John Doe",
};
Exclude 类型
Exclude 类型用于从一个类型中排除指定的类型,从而创建一个新的类型。其语法如下:
type Exclude<T, U> = T extends U ? never : T;
其中:
T
是要从中排除类型的类型。U
是要从T
中排除的类型。
例如,我们可以使用 Exclude 类型从 Number
类型中排除 string
类型,创建一个新的 NotNumber
类型:
type Number = string | number;
type NotNumber = Exclude<Number, string>;
现在,NotNumber
类型只包含 number
类型:
const number: NotNumber = 123;
ThisParameterType 类型
ThisParameterType 类型用于获取函数的 this
参数的类型。其语法如下:
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
其中:
T
是要获取this
参数类型的函数。
例如,我们可以使用 ThisParameterType 类型获取 Person
构造函数的 this
参数的类型:
class Person {
constructor(public name: string) {}
}
type ThisParameterType<Person> = Person;
现在,ThisParameterType<Person>
类型是 Person
类型:
const person: ThisParameterType<Person> = new Person("John Doe");
总结
在本文中,我们介绍了 TypeScript 中的 Omit、Exclude 和 ThisParameterType 类型。这些类型可以帮助我们创建更强大和更灵活的类型。