Reputation: 17425
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;
}
Upvotes: 39
Views: 8533
Reputation: 39508
For function expressions:
export type Add = (x: number, y: number) => number
export const add: Add = function add (x, y) {
return x + y;
}
For function declarations:
export function add (x: number, y: number): number
export function add (x: any, y: any) {
return x + y;
}
Upvotes: -1
Reputation: 2575
You can specify types for function expressions but not function declarations.
// index.d.ts
export function add(a: string, b: string): string;
export function add(a: number, b: number): number;
// index.js
/**
* @typedef {import('./index.d.ts').add} AddFunction
*/
/**
* @type AddFunction
* @param {any} a
* @param {any} b
*/
export const add = function(a, b) {
return a + b;
}
add(1, 2);
add('a', 'b');
add(1, '2')
❯ ./node_modules/.bin/tsc
index.js:16:1 - error TS2769: No overload matches this call.
Overload 1 of 2, '(a: string, b: string): string', gave the following error.
Argument of type 'number' is not assignable to parameter of type 'string'.
Overload 2 of 2, '(a: number, b: number): number', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'number'.
16 add(1, '2');
~~~~~~~~~~~
Found 1 error in index.js:16
Upvotes: 0
Reputation: 250246
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;
}
Upvotes: 24