Given the following type:
type Add = (x:number, y:number) => number
I can declare a const
of that type and define the rest of the function without having to specify the types explicitly. Typescript knows that x
is a number and y
is a number.
const add: Add = (x, y) => x y;
I prefer to define functions using function
rather than const
however there doesn't appear to be a way to type the complete function declaration. It appears that you are forced to define the parameters and the return type separately. Is there any way to use the Add
type on the declaration below so that I don't have to specify that x
is a number and y
is a number
function add(x, y) {
return x y;
}
without being forced to do something like
function add(x: Parameters<Add>[0], y: Parameters<Add>[1]): ReturnType<Add> {
return x y;
}
CodePudding user response:
You can't specify types for function declarations. You can only use Parameters
and ReturnType
. The only minor improvement would be to use destructuring for the parameters:
type Add = (x:number, y:number) => number
function add(...[x, y]: Parameters<Add>): ReturnType<Add> {
return x y;
}