When working with TypeScript, I've noticed that it usually infers the type correctly without me having to explicitly define it. For example:
function myFunction<T>(callback: () => T) {
return callback();
}
const result = myFunction(() => 5); //The type of "result" is automatically inferred as a Number.
However, I encountered an issue when trying to use this inference inside an object. TypeScript requires me to explicitly specify the type:
type MyObject<T> = {
callback: ()=>T
}
const myObject: MyObject = { //An error occurs here and the compiler asks for a type definition.
callback: ()=>5
}
Even though it's clear that "callback" is a function that returns a Number, TypeScript doesn't seem to recognize this. Is there a way to work around this limitation?