The following code throws:
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]))
Instead of listing all possible keys:
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]))
Is there a better way for fixing this error?
One-liner:
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]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.