Why can this type not be inferred?

I have a function that accepts two function arguments, callback and getValue. I'm wondering why the callback's argument cannot be inferred when I do this: callback(getValue({ value: 1 })).

Playground link.

It works if I reverse the argument order. I assume this is because the type of value (line 14) cannot be inferred until the function type on the next line is analyzed.

Posted Oct 16, 2019, 11:08 PM UTC · edited

22
williams-j•

In general, type inference works left-to-right.

The type parameter T in the getValue argument is in an input (negative) position. The type parameter T in the callback argument is in an output (positive) position. Inferring negative type parameters can be done by just looking at the types of the arguments; inferring positive type parameters needs some form of unification, which only really works if you already previous inferences built up.

This is why having the type with the negative parameter before the positive one is better - the easy inferences from the negative parameter in the first argument flow to the positive parameter in the second argument.

4
charliemei•

you can do as follow:

type Obj = {
value: number;
};
function call<T>(
callback: (value: T) => any,
getValue: (obj: Obj) => T,
) {
const value = getValue({ value: 1 });
callback(value);
}

call<number>(
value => value / 3,
obj => obj.value,
);

if you don`t specify the T,typescript will infer type automatically. In function named callback , value is as a parameter which ts can`t infer type. You should put function getValue before

1