【发布时间】:2020-07-27 19:16:31
【问题描述】:
在 Typescript 3.7 中引入了 nullish coalescing operator。对于像
这样的情况,它似乎是完美的类型保护const fs = (s: string) => s
const fn = (n: number) => n
let a: string | null | undefined
let b: number | null | undefined
const x = (a ?? null) && fs(a)
const y = (b ?? null) && fn(b)
但是,如果您将该代码放入 typescript playground,它会提醒您传递给 fs / fn 函数的 a 和 b 参数,例如:
我进行了进一步的实验,发现它不仅是一个孤立于无效合并运算符的问题,而且当 typescript 能够使用 soemthing 作为 typeguard 时,我无法改变主意(在下面找到some examples)
最后两行最让我困惑。在我看来,分配给 x7 和 x8 的两个表达式都是完全等价的,但是在分配给 x8 的表达式中,类型保护工作,对于 x7 表达式中的打字稿来说似乎并不合适:
const fs = (str: string) => str
const create = (s: string) => s === 's' ? 'string' : s === 'n' ? null : undefined
const a: string | null | undefined = create('s')
const b: string | null | undefined = 's'
let x
if (a !== null && a !== undefined) {
x = a
} else {
x = fs(a)
}
const x1 = a !== null && a !== undefined && fs(a)
const x2 = a !== null && a !== void 0 && fs(a)
const x3 = (a ?? null) && fs(a)
const x4 = (b ?? null) && fs(b)
const x5 = a !== null && a !== undefined ? a : fs(a)
const something = a !== null && a !== undefined
const x6 = something ? a : fs(a)
const x7 = something && fs(a)
const x8 = (a !== null && a !== undefined) && fs(a)
我不确定,如果打字稿由于某种原因无法应用类型保护,或者它实际上是打字稿中的错误。那么,当 typescript 可以应用 typeguard 时,是否有规则手册?或者它可能是一个错误?还是有其他原因我没有编译这些示例?
顺便说一句。当使用用户定义的类型保护时,当然可以完美地工作,但最好不必添加一些运行时代码来使类型保护工作。
【问题讨论】:
-
我认为在您的示例中使用
??没有任何意义。a ?? null在所有情况下都只是a,除了a === undefined,在这种情况下它是null。 -
如果您希望
(a ?? null) && fs(a)表示“如果a无效,则null或fs(a)否则”,那么,这不是它的意思。 -
你是对的,a ??如果没有它来自的原始上下文,null 可能没有多大意义,它只是为了缩小类型并消除 null 和 undefined,但最终它没有任何区别,如果你用 ?? fs(a) ??运算符仍然不能作为类型保护。我的观点是,当 typescript 到达将 a 传递给 fs 的点时,我希望它应该很清楚,它不能再为 null 或 undefined 了,对吧?
-
?? fs(a)更加错误,因为如果a为空或未定义,则仅评估fs(a)。 -
对此我还没有权威的答案,但是编译器不会将控制流分析分配给每个联合类型的每个可能成员,因为这通常会非常昂贵。相反,它使用启发式方法使常见的编程习惯用作类型保护。我怀疑像
(a ?? null) && fs(a)这样的东西是否足够“常见”。虽然仍在寻找“官方”答案
标签: typescript typeguards nullish-coalescing