Home > Mobile >  TypeScript does not infer callback return type in an object
TypeScript does not infer callback return type in an object

Time:12-21

TypeScript infers type correctly in this case, without me explicitly giving a type.

function myFunction<T>(callback: () => T) {
     return callback();
}

const result = myFunction(() => 5); //TypeScript knows that "result" type is a Number.

But it's not working inside an object, TypeScript forces me to explicitly give a type.

type MyObject<T> = {
    callback: ()=>T
}

const myObject: MyObject = { //Error happens, the compiler ask for a type here.
    callback: ()=>5
}

But compiler should know that "callback" is a function that return a Number. Is there a way to fix this?

CodePudding user response:

TypeScript doesn't currently have the concept of inferring type arguments in generic types the way it does when you call generic functions. There is a feature request at microsoft/TypeScript#26242 which, if implemented, would allow the use of some sigil to tell the compiler to infer a particular type argument. So maybe, some day in the future, you'd be able to write const myObject: MyObject<infer> = ... or const myObject: MyObject<*> = ... or even const myObject: MyObject = ... and get the behavior you're looking for. But right now it's not part of the language.

The only way to get such behavior now is to use a generic helper identity function that returns its input:

const asMyObject = <T,>(m: MyObject<T>) => m;

So instead of const myObject: MyObject = ... you would write const myObject = asMyObject(...) and get the same effect:

const myObject = asMyObject({
    callback: () => 5
});

// const myObject: MyObject<number>

Here the compiler has inferred T to be number in the call to asMyObject(), and so the value returned from asMyObject() is of type MyObject<number>, and therefore so is the myObject variable.

Playground link to code

  • Related