TypeScript中的方括号表示法和点表示法与”noImplicitAny”:true/false的区别

huangapple go评论81阅读模式
英文:

TypeScript bracket notation and dot notation differences with "noImplicitAny": true/false

问题

With "noImplicitAny": true in tsconfig.json:

const a = {}
console.log(a['b']) // 👈 属性 b 在类型 {} 上不存在。
console.log(a.b) // 👈 属性 b 在类型 {} 上不存在。

With "noImplicitAny": false in tsconfig.json:

const a = {}
console.log(a['b']) // 👈 没有错误
console.log(a.b) // 👈 属性 b 在类型 {} 上不存在。

为什么第二个 console.log(a['b']) 没有错误,而第二个 console.log(a.b) 报错?

英文:

With "noImplicitAny": true in tsconfig.json:

const a = {}
console.log(a['b']) // 👈 Property b does not exist on type {}.
console.log(a.b) // 👈 Property b does not exist on type {}.

With "noImplicitAny": false in tsconfig.json:

const a = {}
console.log(a['b']) // 👈 no error
console.log(a.b) // 👈 Property b does not exist on type {}.

Why there's no error for the second console.log(a['b']) while the second console.log(a.b) throws?

答案1

得分: 0

使用方括号表示法是有意允许的,以便您可以执行否则被禁止的索引。因此,如果 foo.bar 被禁止,您可以使用 foo["bar"] 来绕过它。但是,当您这样做时,如果属性不存在,生成的属性类型将隐式为 any。因此,仅当启用 --noImplicitAny 时,您才会收到错误信息。

当启用 --noImplicitAny 时,您会注意到 a["b"] 的错误与 a.b 的错误不同。它们都提到了 b 不存在于类型 {} 上,但对于 a["b"],您还会得到:元素具有隐式的 'any' 类型,因为类型为 '“b”' 的表达式无法用于索引类型 '{}'。

英文:

See microsoft/TypeScript#43431 for an authoritative answer to this question.

Using bracket notation is intentionally allowed so that you can perform otherwise prohibited indexes. So if foo.bar is disallowed, you can work around it with foo["bar"]. But when you do that and the property isn't known to exist, the resulting property type is implicitly any. As such, you get an error if and only if --noImplicitAny is enabled.

You'll notice that the error for a["b"] is different from the error for a.b when --noImplicitAny is enabled. They both mention that b doesn't exist on type {}, but for a["b"] you also get: Element implicitly has an 'any' type because expression of type '"b"' can't be used to index type '{}'.

huangapple
  • 本文由 发表于 2023年6月29日 16:57:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定