Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add type / interface to function() declaration? [duplicate]

Tags:

typescript

I have types like this defined in a separate file:

type AddFunc = (a: number, b:number) => number

and am using them to type "fat arrow" functions:

const add: AddFunc = (a, b) => a + b

This is fine, however I came across an issue when changing above to a function declaration i.e

function add(a, b) {
  return a + b
}

I'm not sure, but is there a way to re-use AddFunc type for above?The only approach I figured out is to do it manually like below, but I wonder if I can reuse existing types instead

function add(a: number, b: number): number {
   return a + b
}
like image 739
Ilja Avatar asked Sep 09 '26 05:09

Ilja


1 Answers

...I wonder if I can reuse existing types instead

Sadly, not really. I mean, you could do something like this (playground link):

function add(...args: Parameters<AddFunc>): ReturnType<AddFunc> {
    const [a, b] = args;
    return a + b;
}

...but while that means you only have to update one place (AddFunc) if doing this with multiple functions of the same type, it's hardly concise. :-)

It does offer good IDE auto-complete etc., though, thanks to the Parameters tuple type:

Screenshot showing TypeScript playground with call to add with the cursor just after the opening ( showing the playground prompting the user with the a and b parameters and their types

like image 195
T.J. Crowder Avatar answered Sep 12 '26 21:09

T.J. Crowder