The explicit generic type was not provided in the call to empty()
here:
const b = abc ?? empty()
However, Typescript can deduce that type from the expression - it recognizes that abc
is of type number[] | null
, so it infers that the type parameter for the empty
call is number
(this information can be seen by hovering over empty()
in the playground). Therefore, your line essentially becomes:
const b = abc ?? empty<number>();
Hence, 'b' is also of type number[]
. It's important to note that omitting the generic type parameter does not default to unknown
.
Regarding how exactly type inference operates - there isn't a strict specification available to refer to. The latest version has been archived and no longer updated. There have been some changes made to the type inference rules compared to this archived version. Therefore, the most reliable source of information would be the official documentation, which provides somewhat vague explanations. The section relevant to this topic is called "Contextual Typing," where it broadly explains that Typescript can infer generic type parameters based on context in many scenarios, without detailing exactly how.
In this specific scenario, however, the situation appears quite straightforward. The known type on the left side of the ?? expression allows for the same type to be used on the right side with the generic type parameter omitted.