如何从Typescript中的函数获取参数类型 [英] How to get argument types from function in Typescript
问题描述
我可能遗漏了文档中的某些内容,但我在打字稿中找不到任何方法来获取函数中参数的类型.也就是说,我有一个函数
I may have missed something in the docs, but I can't find any way in typescript to get the types of the parameters in a function. That is, I've got a function
function test(a: string, b: number) {
console.log(a);
console.log(b)
}
我想访问类型 string
和 number
,可能是元组.
I want access to the types string
and number
, likely as a tuple.
我知道我可以获取函数本身的类型,如 typeof test
,或者通过 ReturnType
获取返回类型.
I know I can get the type of the function itself, as typeof test
, or the return type via ReturnType<test>
.
当我尝试keyof typeof test
时,它返回never
,我也无法解释.
When I tried keyof typeof test
, it returned never
, which I also couldn't explain.
其他答案像这个指向extends
,但我真的不明白它是如何工作的,也没有给我一个简单的方法来访问 set-of-all-params 作为一种类型.
Other answers like this one point to extends
, but I don't really understand how that works and don't give me an easy way to access the set-of-all-params as a type.
推荐答案
Typescript 现在带有 标准库中预定义的Parameters
类型别名,与ArgumentTypes<>几乎相同
下面,所以你可以使用它而不是创建你自己的类型别名.
Typescript now comes with a predefined Parameters<F>
type alias in the standard library which is almost the same as ArgumentTypes<>
below, so you can just use that instead of creating your own type alias.
type TestParams = Parameters<(a: string, b: number) => void> // [string, number]
然后要获取例如第二个参数的类型,您可以使用数字索引运算符:
Then to get for example the second parameter's type you can use the numeric indexing operator:
type SecondParam = TestParams[1] // number
原答案:
是的,现在 TypeScript 3.0 引入了处于静止/展开位置的元组,您可以创建一个条件类型来做到这一点:
Yes, now that TypeScript 3.0 has introduced tuples in rest/spread positions, you can create a conditional type to do this:
type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;
让我们看看它是否有效:
Let's see if it works:
type TestArguments = ArgumentTypes<typeof test>; // [string, number]
看起来不错.请注意,这些增强的元组还捕获了诸如可选参数和其余参数之类的内容:
Looks good. Note that these beefed-up tuples also capture things like optional parameters and rest parameters:
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[]]
希望有所帮助.祝你好运!
Hope that helps. Good luck!
这篇关于如何从Typescript中的函数获取参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!