Contextual Typing in TypeScript is an interesting feature where the correct type is inferred from the return value when a generic type is not specified.
While it usually works well, there are instances where it can be unpredictable. For example, in some cases, if a function parameter is undefined, the default generic type may not be used as expected.
👇 Check out this TypeScript Playground link
type State = { count: number }
declare function simple<T = State>(second?: T): T;
const { count: countA } = simple()
// in 4.0+ => countA: number
// in 3.9 => countA: any;
declare function complex<M, T = State>(first: M, second?: T): T;
const { count: countB } = complex(1)
// countB: any;
I'm curious to know if this behavior in TypeScript is a bug or if there's a specific priority in determining which type to infer, whether it's the return type or the generic default type.