Say, I have a function like this:
function plus(a: number, b: number) { return a + b }
Of course, it's type is (a: number, b: number) => number
as function in Typescript.
If I want to use this function as an "argument" for another without really declare its type, I could use the default argument trick:
function wrap(fn = plus) { ... }
If I don't want it to be the default argument, do I have any other choice besides explicitly declare its type ?
In short, I don't want this function wrap(fn: (a: number, b: number) => number) { ... }
, but I do want something like this function wrap(fn: like(plus)) { ... }
.
Thanks to @OweR ReLoaDeD, type fn = typeof plus
is a valid statement, so this works:
function plus(a: number, b: number) { return a + b }
function wrap(fn: typeof plus) { }
What about using generics:
function plus(a: number, b: number) { return a + b }
function wrap<T extends Function>(fn: T) {
fn();
}
// Works
var wrappedPlus = wrap<typeof plus>(plus);
// Error: Argument of type '5' is not assignable to parameter of type '(a: number, b: number) => number'.
var wrappedPlus = wrap<typeof plus>(5);
// Error: Argument of type '5' is not assignable to parameter of type 'Function'.
var wrappedPlus = wrap(5);
function concat(a: string, b: string) { return a + b }
// Error: Argument of type '(a: number, b: number) => number' is not assignable to parameter of type '(a: string, b: string) => string'.
var wrappedPlus = wrap<typeof concat>(plus);
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