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?
Top comments (3)
Well you almost get it ! I suggest to be more specific on the types, to prevent dumb errors and to get autocompletion:
See this TS Playground
The point is to NOT make type assertion by using the
as
keyword which is considered a bad practice, use it only when there's no other choice.Thanks!!
I would like to avoid this
I don't like the repetition, any suggestion?
--EDIT--
Using your idea, I can update the code to:
(note: I removed the
|0
for now)Playground
Yes it's good. It's preferable to also type variables (const, let, - avoid var)
The important point is the function parameter type
animal: keyof typeof mappingAnimalLegs
so that you get autocompletion & type error earlyAlso be careful, it might seems you've done a typo error:
getLegsNamber--> getLegsNumber