为什么 a = null ? [] 类型 never[]?
Why is a = null ?? [] of type never[]?
为什么我在这里对数组进行不同的类型推断?
const a = []; // any[]
const b = null ?? []; // never[]
“正确”的做法是为空数组文字 []
推断 never[]
,因为数组文字的类型是其元素类型的连接,并且never
是一个空集的连接。
然而,由于推断 never[]
通常不是用户在编写 const a = []
时的意图,因此这种特殊情况收到了 very special treatment in the compiler,现在它开始隐式推断 any[]
,然后根据后续的控制流程细化类型
它背后似乎没有任何更深层次的含义:它只是在大多数情况下被证明是最有用的。
为什么我在这里对数组进行不同的类型推断?
const a = []; // any[]
const b = null ?? []; // never[]
“正确”的做法是为空数组文字 []
推断 never[]
,因为数组文字的类型是其元素类型的连接,并且never
是一个空集的连接。
然而,由于推断 never[]
通常不是用户在编写 const a = []
时的意图,因此这种特殊情况收到了 very special treatment in the compiler,现在它开始隐式推断 any[]
,然后根据后续的控制流程细化类型
它背后似乎没有任何更深层次的含义:它只是在大多数情况下被证明是最有用的。