ReturnType<T>
extracts return type of a function.
Is there a way to define ArgumentsType<T>
that extracts parameter types of a function in tuple
format?
For example,
ArgumentsType<(a: number, b: string) => boolean>
will be [number, string]
.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
In TypeScript we can express its type as: ( a : number , b : number ) => number. This is TypeScript's syntax for a function's type, or call signature (also called a type signature). You'll notice it looks remarkably similar to an arrow function—this is intentional!
Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.
TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.
Edit
Since writing the original answer, typescript now has a built-in type (defined in lib.d.ts
) to get the type of the parameters called Parameters
type argsEmpty = Parameters<() => void> // [] type args = Parameters<(x: number, y: string, z: boolean) => void> // [number, string, boolean] type argsOpt = Parameters<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]
Edit Typescript 3.0 has been relesed the code below works as expected.
While this is not possible in the current version of typescript (2.9) without spelling out all parameters. It will become possible in the next version of typescript (3.0) which will be released in the next few days:
type ArgumentsType<T> = T extends (...args: infer U) => any ? U: never; type argsEmpty = ArgumentsType<() => void> // [] type args = ArgumentsType<(x: number, y: string, z: boolean) => void> // [number, string, boolean] type argsOpt = ArgumentsType<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]
If you install npm install typescript@next
you can already play with this, it should be available sometime this month.
Note
We can also spread a tuple into arguments with this new feature:
type Spread<T extends any[]> = (...args: T)=> void; type Func = Spread<args> //(x: number, y: string, z: boolean) => void
You can read more about this feature here
As of TypeScript 3.1, Parameters
type is now a part of the standard library.
type Result = Parameters<(a: number, b: string) => boolean>; // [number, string]
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