【问题标题】:How to preserve type guard narrowing when using logical assignment?使用逻辑赋值时如何保持类型保护缩小?
【发布时间】: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 在第二种情况下失去缩小范围的原因是什么?

Playground

【问题讨论】:

标签: typescript typeguards type-narrowing typescript4.0 compound-operator


【解决方案1】:

在源存储库中将此作为issue 提交后,该行为已被确认为错误(更像是设计限制,因为在使用逻辑赋值运算符而不是短路时未进行控制流分析用逻辑运算符赋值)。

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 2015-10-10
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2020-09-03
    • 2020-10-21
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多