3

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

1 Answer 1

2

...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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.