When using TypeScript, there seems to be an issue with properly inferring the generic type of a function that accepts another function. This inner function, in turn, exposes its argument as a function which requires a generic argument when called.
const notWorking = <Value>(callback: (emitValue: (value: Value) => void) => void): void => {
//...
}
notWorking((emitValue) => {
emitValue(123);
});
Instead of inferring the correct type, the notWorking
function here treats the generic argument as unknown
, even though the value passed to emitValue
is of type number
.
I attempted to set a default value for the Value
generic parameter using never
, hoping it would at least trigger an error and prompt me to provide a specific type. While this workaround works in the code snippet below:
const notWorking = <Value = never>(callback: (emitValue: (value: Value) => void) => void): void => {
//...
}
notWorking<number>((emitValue) => {
emitValue(123);
});
Unfortunately, I am now required to explicitly define the generic type every time. Is there a way to improve TypeScript's inference abilities for such higher-order functions, or is this a limitation of the language itself?
For my scenario, using a generic within the passed function is not a feasible solution.