TypeScript: Unexpected unknown
This is a design limitation in TypeScript; see microsoft/TypeScript#38845. Apparently (from this comment):
An arrow function with no parameters is not context sensitive, but a function expression with no parameters is context sensitive because of the implicit
this
parameter. Anything that is context sensitive is excluded from the first phase of type inference, which is the phase that determines the types we'll use for contextually typed parameters.
It looks like inference for T
succeeds when the foo.bar
property is an arrow function because there's no contextual this
to worry about. And so a contextual type is successfully assigned to the x
parameter of g
, and everything proceeds as you want. But when the value of foo.bar
is a function expression, the compiler needs context to figure out what this
is, and T
cannot be inferred in time to figure out a contextual type for g
's parameter and it ends up becoming unknown
.