【发布时间】:2021-05-21 00:44:35
【问题描述】:
以下是重现问题的示例:
type F = () => number;
type R = {
[ x: string ]: R | F | undefined
}
const isFunc = <T extends (...args: any[]) => any>(maybe:unknown) : maybe is T => typeof maybe === "function";
const check = (i: R) => {
let tmp:R = i;
let curr = tmp["something"];
if( isFunc<F>(curr) ) return;
curr // R | undefined, expected
tmp = curr || (curr = {}); //ok, expected
tmp = curr ||= {}; //Index signature is missing in type 'F'
};
如您所见,在类型保护之后,curr 正确地缩小为 R | undefined。之后,我将tmp 重新分配给curr,并在缺少时将后者默认为空对象。
现在,如果使用 A || A = B 方法,逻辑 OR 左侧的 curr 会正确缩小为 R | undefined。但是,如果我使用逻辑 OR 分配使意图更清晰,curr 会被推断为R | F | undefined。这显然会导致错误,因为F 不能分配给R。
问题是 - curr 在第二种情况下失去缩小范围的原因是什么?
【问题讨论】:
-
第 21 行的等号是什么 (
curr ||= {})? -
@Teneff,嗯,对于logical OR assignment operator(或this)——我错过了什么吗?
标签: typescript typeguards type-narrowing typescript4.0 compound-operator