在 TypeScript 中获取函数参数的类型
使用 Parameters
实用程序类型获取函数参数的类型,例如 type SumParams = Parameters<typeof sum>
。 Parameters
实用程序类型根据函数参数中使用的类型构造元组类型
function sum(a: number, b: string): string {
return a + b;
}
// 👇️ type SumParams = [a: number, b: string]
type SumParams = Parameters<typeof sum>;
// 👇️ type FirstParam = number
type FirstParam = SumParams[0];
// 👇️ type SecondParam = string
type SecondParam = SumParams[1];
Parameters
实用程序类型根据函数参数中使用的类型构造元组类型。
我们可以使用方括号访问特定参数的类型,就像访问索引处的数组元素一样。
下面是一个示例,说明如何将 Parameters
实用程序类型用于两个采用相同对象作为参数的函数。
type Person = {
name: string;
age: number;
country: string;
};
function getObj(obj: Person): Person {
return obj;
}
function getObj2(obj: Parameters<typeof getObj>[0]) {
return obj;
}
console.log(getObj2({ name: 'Tom', age: 30, country: 'Chile' }));
getObj2
函数采用与 getObj
函数采用的对象类型相同的对象。
请注意
,在我们获得参数类型的元组后,我们必须访问索引 0 处的元素以获取对象的类型。
type Person = {
name: string;
age: number;
country: string;
};
function getObj(obj: Person): Person {
return obj;
}
// 👇️ type GetObjParams = [obj: Person]
type GetObjParams = Parameters<typeof getObj>
这是因为 Parameters
实用程序类型返回一个元组,即使该函数采用单个参数也是如此。
如果需要获取类中构造函数方法的参数类型,请改用 ConstructorParameters
实用程序类型。
class Person {
constructor(public name: string, public age: number) {
this.name = name;
this.age = age;
}
}
// 👇️ type PersonParams = [name: string, age: number]
type PersonParams = ConstructorParameters<typeof Person>;
// 👇️ type FirstParam = string
type FirstParam = PersonParams[0];
// 👇️ type SecondParam = number
type SecondParam = PersonParams[1];
ConstructorParameters
实用程序类型根据构造函数的参数类型构造一个元组。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。