相关疑难解决方法(0)

Typescript:当密钥存储在变量中时,类型缩小不适用于“in”

考虑这个简单的片段。我也把它粘贴在这里:

type A =
  | {
      b: number;
    }
  | {
      c: number;
    };

function f1(a: A) {
  if ('b' in a) {
    return a['b']; // No problem!
  }
  return 42;
}

function f2(a: A) {
  const key = 'b';
  if (key in a) {
    return a[key];  // Property 'b' does not exist on type 'A'
  }
  return 42;
}
Run Code Online (Sandbox Code Playgroud)

为什么 of 的类型没有a缩小为{b: number}in f2?(因为它是为了f1

typescript type-narrowing

7
推荐指数
1
解决办法
3763
查看次数

标签 统计

type-narrowing ×1

typescript ×1