【问题标题】:Why is a = null ?? [] of type never[]?为什么 a = null ?永不[]类型的[]?
【发布时间】:2022-01-22 23:11:07
【问题描述】:

为什么我在这里得到不同的数组类型推断?

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

Demo here

【问题讨论】:

标签: typescript type-inference typescript-never


【解决方案1】:

“正确”的做法是为空数组字面量[] 推断never[],因为数组字面量的类型是其元素类型的连接,而never 是连接一个空集。

然而,由于推断never[]通常不是用户在编写const a = []时想要的,所以这个特殊情况收到了very special treatment in the compiler,现在它首先隐式推断any[],然后根据后续的控制流程。

它背后似乎没有任何更深层次的含义:它只是在大多数情况下被证明是最有用的。

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 2021-07-06
    • 2012-02-13
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多