I'm learning, So I have the next code...
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr= ["one","one","two","one","three"]
arr.map((each)=>numbers[each])
If I do numbers["one"]
I get "1", but it is not working with the array, for the previous code I get:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type.
I want to use an array of strings in a dictionary as a keys, but I don't know how to do it.
Thanks for your help.
I found the Solution just added to my code : Record<string, any>
CodePudding user response:
In your comment, you've noted that you are getting the following error message
"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type"
Because of the type of your array, each
is typed as string
. That means "any possible string value". So it could be "one" or "two", but it could also be "" or "BorisJohnson" or "Fish".
That presents a problem, because you've used that value to index an object literal which ONLY has the keys "one", "two" or "three".
There are two ways to handle this problem, the first is to give your original object literal an index signature
const numbers: { [key: string]: string} = {
one: "1",
two: "2",
three: "3"
}
const arr = ["one", "one", "two", "one", "three"]
arr.map((each) => numbers[each])
However, this is problematic because in the scenario where your array contains values not in the object, the array returned from your map will be typed string[]
, when in actual fact it should be (string | undefined)[]
(because undefined
is what you get when you index an object with a key not actually included in an object).
My preferred solution here would be to provide a more strict type for your array:
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr: (keyof typeof numbers)[] = ["one", "one", "two", "one", "three"]
arr.map((each) => numbers[each])
This is a smarter approach because in the event you try to put something into that array that wasn't originally a key of your object, the compiler will throw an error. Because of this compiler error, your each
variable is now guaranteed to be one of the keys of numbers
, so will be typed "one" | "two" | "three"
.
It makes sense therefore that whenever you index numbers
with one of its keys, you will only ever get a string, and so your array will be typed correctly.