I am trying to consume an API using javascript.
An endpoint can give me an object with unique keys each time, for example:
{
"-MKlw6VSTSf-FPBaTxfB": {
"created_at": 1603934385.9833121,
"jugadores": 0,
"posiciones": 4
},
"-MKlxam1Zjtz14wZgMNp": {
"created_at": 1603934776.2540152,
"jugadores": 0,
"posiciones": 4
},
"-MKm8JvbKJmMAumJbmoU": {
"created_at": 1603937848.809657,
"jugadores": 0,
"posiciones": 4
},
"-ML3-HtshKPcKrME5Jk6": {
"created_at": 1604237470.857504,
"jugadores": 0,
"posiciones": 4
}
}
Or it can give me an error like this one:
{
"error": true,
"mensaje": "Hubo un error"
}
I have declared this types:
type APIError = {
error: boolean
mensaje: string
}
type ListadoJuegosPublicos = {
[key:string]: {
jugadores: number
posiciones: number
created_at: number
}
}
And I have this function signature to retrieve the data:
async juegosPublicos ():Promise<APIError|ListadoJuegosPublicos>
The function works as expected. But when I try to iterate over the response, I get this error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'APIError | ListadoJuegosPublicos'.
No index signature with a parameter of type 'string' was found on type 'APIError | ListadoJuegosPublicos'.ts(7053)
This is the code I am trying to use to iterate over objects
const juegos = await api.juegosPublicos()
if (juegos.error && typeof juegos.mensaje === 'string') {
console.error(mensaje)
return
}
Object.keys(juegos).forEach((juegoId:string) => {
console.log(juegos[juegoId]) // <- this is the line than generates the error
})
How can I correctly iterate over this object in typescript