如何从Typescript中的函数获取参数类型
我可能在文档中遗漏了一些内容,但我在typescript中找不到任何方法来获取函数中的参数类型。也就是说,我有一个函数如何从Typescript中的函数获取参数类型,typescript,Typescript,我可能在文档中遗漏了一些内容,但我在typescript中找不到任何方法来获取函数中的参数类型。也就是说,我有一个函数 function test(a: string, b: number) { console.log(a); console.log(b) } 我想要访问类型字符串和数字,可能是一个元组 我知道我可以获取函数本身的类型,如typeof test,或者通过ReturnType获取返回类型 当我尝试测试类型的键时,它返回了never,我也无法解释 其他答案指向扩展,
function test(a: string, b: number) {
console.log(a);
console.log(b)
}
我想要访问类型字符串
和数字
,可能是一个元组
我知道我可以获取函数本身的类型,如typeof test
,或者通过ReturnType
获取返回类型
当我尝试测试类型的键时,它返回了never
,我也无法解释
其他答案指向扩展
,但我真的不明白它是如何工作的,也没有给我一个简单的方法来访问所有参数集作为一个类型。一个可能的解决方案是使用参数
变量(这是一个可在所有函数中访问的局部变量,并包含传递给该函数的每个参数的条目)。因此,您可以执行以下操作:
const args = Array.prototype.slice.call(arguments, 0, arguments.length);
const argTypes = args.map(e => typeof e);
console.log(argTypes);
这张照片是:
["string", "number"]
Typescript现在提供了一个与下面的ArgumentTypes
几乎相同的类型,因此您可以使用它而不是创建自己的类型别名
type TestParams = Parameters<(a: string, b: number) => void> // [string, number]
原始答复:
是的,现在TypeScript 3.0已经引入,您可以创建一个条件类型来执行此操作:
type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;
typeargumenttypes=F扩展(…args:infera)=>any?A:never;
让我们看看它是否有效:
type TestArguments = ArgumentTypes<typeof test>; // [string, number]
类型TestArguments=ArgumentTypes;//[字符串,数字]
看起来不错。请注意,这些增强元组还捕获可选参数和rest参数:
declare function optionalParams(a: string, b?: number, c?: boolean): void;
type OptionalParamsArgs = ArgumentTypes<typeof optionalParams>;
// [string, (number | undefined)?, (boolean | undefined)?]
declare function restParams(a: string, b: number, ...c: boolean[]): void;
type RestParamsArgs = ArgumentTypes<typeof restParams>;
// [string, number, ...boolean[]]
声明函数optionalParams(a:字符串,b:数字,c:布尔值):void;
类型OptionalParamsArgs=参数类型;
//[字符串,(数字|未定义),(布尔值|未定义)]
声明函数restParams(a:string,b:number,…c:boolean[]):void;
类型RestParamsArgs=参数类型;
//[字符串,数字,…布尔值[]]
希望有帮助。祝你好运!恐怕我不太明白:你想从a
和b
获得string
和number
吗?我想获得[string,number]
或类似的东西(可能是元组)通过对函数test
应用某种类型的操作,@jcalz。看来这个函数现在在TypeScript本身中作为参数可用。推断
关键字的意思是什么?请看,我以为这个想法是为了识别类型系统中的参数,而不是运行时。
declare function optionalParams(a: string, b?: number, c?: boolean): void;
type OptionalParamsArgs = ArgumentTypes<typeof optionalParams>;
// [string, (number | undefined)?, (boolean | undefined)?]
declare function restParams(a: string, b: number, ...c: boolean[]): void;
type RestParamsArgs = ArgumentTypes<typeof restParams>;
// [string, number, ...boolean[]]