typescript - 类型缩小 : checking variable object key existence when noUncheckedIndexedAccess is true

标签 typescript strictnullchecks

我的 tsconfig.json 中有 "noUncheckedIndexedAccess": true。该开关的全部目的是在访问索引之前强制检查该项目是否存在。

👉我很难用可变键检查对象:

假设我有以下结构:

const items: Record<string, {name: string}> = {
  '123': {
    name: 'asdf'
  }
}

当我尝试使用文字键检查是否存在时,类型缩小工作正常:

if (items['123']) {
  // OK: Compiles no problem
  console.log(items['123'].name)
}

如果我尝试使用变量键检查是否存在,编译器就会开始提示。

const id = '123';
if (items[id]) {
  // ERROR: items[id] - Object possibly undefined
  console.log(items[id].name)
}

👉为什么不能通过这种方式检查存在性?

我尝试了不同的检查:

if (id in items) {}
if (items.hasOwnProperty(id)) {}
if (typeof items[id] !== 'undefined') {}

运气不好。

唯一有效的是

const id = '123';
const item = items[id];
if (item) {
  // OK
  console.log(item.name)
}

不过我觉得有点太啰嗦了。

▶️ Examples above in TypeScript Playground

环境: TypeScript v4.5.4

最佳答案

GitHub 上有一个问题本质上描述了这种具体情况:

Can't narrow T | undefined into T with a falsy check when using --noUncheckedIndexedAccess

该问题作为此问题的重复项已关闭,截至 2022 年 2 月,该问题仍处于开放状态:

Discriminant property type guard not applied with bracket notation

根据对第二个问题和其他相关问题的讨论,听起来这是一个已知的限制,因为在类型检查器中实现这一点需要性能开销,例如here :

Declined due to performance reasons. Since it should almost always be possible to write const j = list[i] instead, this shouldn't be too burdensome.

鉴于该问题仍然悬而未决,似乎可能会在某个时候重新解决这个问题以支持您期望的行为。

关于typescript - 类型缩小 : checking variable object key existence when noUncheckedIndexedAccess is true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71035269/

相关文章:

typescript - 如何使用角度 Material 树以角度 6 保存选中的节点?

Angular - mat-slide-toggle 不可见

javascript - 在一个函数/方法上使用 'strictNullChecks' 注释

javascript - typescript :使用 Map<> with strictNullChecks

typescript 和过滤器 bool 值

angular - 如何在 Angular 4 中实现 strictNullChecks

angular - 如何只在需要时加载 Zone.js

typescript - 嵌套类型的模板文字类型

java - TypeScript 相当于 ParentClass.this 是什么