以下代码抛出:
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]))有更好的方法来修正这个错误吗?
发布于 2021-05-20 11:17:50
单线:
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]))https://stackoverflow.com/questions/67619248
复制相似问题