英文:
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 '{}'.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论