首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >元素隐式具有'any‘类型,因为类型'any’的表达式不能用于索引类型{ 1: number;2: number;3: number;}‘

元素隐式具有'any‘类型,因为类型'any’的表达式不能用于索引类型{ 1: number;2: number;3: number;}‘
EN

Stack Overflow用户
提问于 2021-05-20 11:14:01
回答 1查看 269关注 0票数 1

以下代码抛出:

代码语言:javascript
复制
Element implicitly has an 'any' type because the expression of type 'any' can't be used to index type '{ 1: number; 2: number; 3: number; }'.
代码语言:javascript
复制
const obj = {
  1: 1,
  2: 2,
  3: 3,
}

fetch('http://example.com/foo.json')
  .then(response => response.json())
  //                         throws
  .then(data => console.log(obj[data]))

而不是列出所有可能的键:

代码语言:javascript
复制
const obj = {
  1: 1,
  2: 2,
  3: 3,
}

fetch('http://example.com/foo.json')
  .then(response => response.json())
  //                                  list all possible keys
  .then(data => console.log(obj[data as 1 | 2 | 3]))

有更好的方法来修正这个错误吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-20 11:17:50

单线:

代码语言:javascript
复制
const obj = {
  1: 1,
  2: 2,
  3: 3,
}

fetch('http://example.com/foo.json')
  .then(response => response.json())
  //                                  one-liner
  .then(data => console.log(obj[data as keyof typeof obj]))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67619248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档