在TS中获取类构造函数的参数类型
使用 ConstructorParameters
实用程序类型获取 TypeScript 中类构造函数的参数类型,例如 type T = ConstructorParameters<typeof MyClass>
。 ConstructorParameters
类型返回一个元组类型,其中包含构造函数的参数类型。
// ✅ For constructors of classes
class Person {
constructor(public name: string, public age: number, public country: string) {
this.name = name;
this.age = age;
this.country = country;
}
}
// 👇️ type PersonParamsType = [name: string, age: number, country: string]
type PersonParamsType = ConstructorParameters<typeof Person>;
// 👇️ type First = string
type First = PersonParamsType[0];
// 👇️ type Second = number
type Second = PersonParamsType[1];
// ✅ For regular functions
function sum(a: number, b: number): number {
return a + b;
}
// 👇️ type SumParamsType = [a: number, b: number]
type SumParamsType = Parameters<typeof sum>;
我们使用 ConstructorParameters
实用程序类型来获取所有构造函数参数类型的元组类型。
如果我们需要访问特定参数的类型,例如 第一个,我们可以使用括号表示法并访问特定索引处的元素。
class Person {
constructor(public name: string, public age: number, public country: string) {
this.name = name;
this.age = age;
this.country = country;
}
}
// 👇️ type PersonParamsType = [name: string, age: number, country: string]
type PersonParamsType = ConstructorParameters<typeof Person>;
// 👇️ type First = string
type First = PersonParamsType[0];
// 👇️ type Second = number
type Second = PersonParamsType[1];
// 👇️ type Third = string
type Third = PersonParamsType[2];
元组的索引是从零开始的,就像数组一样。
请注意
,ConstructorParameters
实用程序类型将返回包含参数类型的元组,即使构造函数采用单个参数也是如此。
class Person {
name: string;
age: number;
country: string;
constructor({
name,
age,
country,
}: {
name: string;
age: number;
country: string;
}) {
this.name = name;
this.age = age;
this.country = country;
}
}
// 👇️ type PersonParamsType = [{
// name: string;
// age: number;
// country: string;
// }]
type PersonParamsType = ConstructorParameters<typeof Person>;
// 👇️ type First = {
// name: string;
// age: number;
// country: string;
// }
type First = PersonParamsType[0];
示例中的类采用单个参数 – 一个对象。 但是,ConstructorParameters
仍然返回一个包含该对象的元组。
如果需要访问对象的类型,则需要访问索引为 0 的元组元素。
如果我们需要获取常规函数参数的类型,则应改用 Parameters
实用程序类型。
function sum(a: number, b: number): number {
return a + b;
}
// 👇️ type SumParamsType = [a: number, b: number]
type SumParamsType = Parameters<typeof sum>;
// 👇️ type First = number
type First = SumParamsType[0];
// 👇️ type Second = number
type Second = SumParamsType[1];
Parameters
实用程序类型还返回一个包含所有函数参数类型的元组类型。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。