Search code examples
typescripttype-inferencetypescript-never

Why is a = null ?? [] of type never[]?


Why am I getting different type inference here for the array ?

const a = []; // any[]
const b = null ?? []; // never[] 

Demo here


Solution

  • The "correct" thing to do would be to infer never[] for the empty array literal [], because the type of an array literal is the join of the types of its elements, and never is the join of an empty set.

    However, since inferring never[] is usually not what the user intends when writing const a = [], this particular case received a very special treatment in the compiler, and now it starts by implicitly inferring any[], and then refining the type based on the subsequent control flow.

    There does not seem to be any deeper meaning behind it: it's just what turns out to be the most useful in most cases.