Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Declaring a function signature type like const

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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;
}

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading