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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With