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) }
I want access to the types string
and number
, likely as a tuple.
I know I can get the type of the function itself, as typeof test
, or the return type via ReturnType<test>
.
When I tried keyof typeof test
, it returned never
, which I also couldn't explain.
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.
The error "Duplicate function implementation" occurs when we define an implementation for a function with the same name multiple times in the same file. To solve the error, rename the second function or use overloads by specifying multiple signatures, not multiple implementations.
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.
In TypeScript, function overloading, or method overloading, is the ability to create multiple methods with the same name and same return type, but a different number of parameters or different parameter types.
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
Original answer:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With