typescript - 使用逻辑赋值时如何保持类型保护缩小?

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

以下是重现该问题的示例:

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 。之后,我重新分配 tmpcurr如果后者丢失,则将其默认为空对象。

现在,如果 A || A = B使用方法,curr逻辑 OR 左侧的值被适当缩小为 R | undefined 。但是,如果我使用逻辑或赋值来使意图更清晰,curr推断为R | F | undefined 。这显然会导致错误,因为 F不可分配给R .

问题是 - curr 的原因是什么?在第二种情况下会失去缩小范围吗?

Playground

最佳答案

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

关于typescript - 使用逻辑赋值时如何保持类型保护缩小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66253621/

相关文章:

angular - 获取对模板中组件的引用

typescript - 如何通过 bool 值输入保护?

typescript - 为具有所有可选属性的接口(interface)制作类型保护

typescript - 动态类型保护功能

java - 如果在三元运算符中使用局部变量,为什么从 int 到 short 的缩小转换不起作用

typescript - 有没有办法通过检查函数来实现类型缩小?

javascript - 如何在 VS Code 中使用 d.ts 文件进行智能感知,类似于 NPM 方法

reactjs - Next.Js Redux Wrapper w/Typescript - 实现错误,存储类型不存在

typescript - TypeScript 可以警告我关于非空断言运算符的过度使用吗?

typescript - 控制流不使用联合元组进行类型缩小?