Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Required callback parameters?

Tags:

typescript

I want to define a function which takes a callback as a parameter, and that callback's parameters should be required. Typescript correctly reports a callback with a mismatched parameter type but says nothing about callbacks with no expected arguments.

Why does the second on call not error, and is there any way to make it error?

function on(callback: (num: number) => void) {
    callback(5);
}

on((string:bob) => { // typescript error
    console.log("What");
});

on(() => { // no typescript error?
    console.log("What");
});
like image 205
Jazcash Avatar asked Oct 26 '25 09:10

Jazcash


1 Answers

There isn't a way to do this.

Callbacks with fewer parameters than the caller provides are extremely common in JavaScript - functions like forEach, map, filter, etc all provide 3 or more arguments but are frequently given 1-parameter functions as callbacks.

like image 123
Ryan Cavanaugh Avatar answered Oct 28 '25 23:10

Ryan Cavanaugh



Donate For Us

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