繁体   English   中英

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

[英]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; }'

以下代码抛出:

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; }'.
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]))

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

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]))

有没有更好的方法来修复这个错误?

单线:

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]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM