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 mismatc
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.
You could define a type for the handler. Now you can only pass a callback that has a string argument.
// define a handler so you can use it for callbacks
type Handler = (t: string) => void;
function doSomething(t: string): void {
console.log("hello " + t)
}
function thisFirst(callback: Handler) {
callback('world') // ok
callback(4) // not assignable to type 'string'
}
thisFirst(doSomething)