How-to: Use dictionary in TypeScript

linediconsine

Marco

Posted on June 5, 2024

How-to: Use dictionary in TypeScript

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
}
Enter fullscreen mode Exit fullscreen mode

If I write something like this

function getLegsNumber(animal) {
    return mappingAnimalLegs[animal] | 0
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

I can also simplify a bit more with

function getLegsNumber(animal: string): number {
    return mappingAnimalLegs[animal as keyof typeof mappingAnimalLegs] | 0
}
Enter fullscreen mode Exit fullscreen mode

What do you think?

Typescript playground as reference

πŸ’– πŸ’ͺ πŸ™… 🚩
linediconsine
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