How-to: Use dictionary in TypeScript
Marco
Posted on June 5, 2024
Here is the scenario, I want to create a function getLegsNumber
that use this structure as dictionary
const mappingAnimalLegs = {
'CAT' : 4,
'DOG' : 4,
'DUCK' : 2
}
If I write something like this
function getLegsNumber(animal) {
return mappingAnimalLegs[animal] | 0
}
Typescript is not happy and tell us:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ CAT: number; DOG: number; DUCK: number; }'.(7053)
So... how I can solve this without adding too much noise ?
Here is my solution:
function getLegsNumber(animal: string): number {
if (animal in mappingAnimalLegs) {
return mappingAnimalLegs[animal as keyof typeof mappingAnimalLegs];
}
return 0
}
I can also simplify a bit more with
function getLegsNumber(animal: string): number {
return mappingAnimalLegs[animal as keyof typeof mappingAnimalLegs] | 0
}
What do you think?
π πͺ π
π©
Marco
Posted on June 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How I Created Vanilla Calendar Pro β A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024
typescript π₯ Why TypeScript is the Go-To Language for Modern Web Development π₯
October 16, 2024