映射数组以访问 TypeScript 中的字典值
我正在学习,所以我有下一个代码...
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr= ["one","one","two","one","three"]
arr.map((each)=>numbers[each])
如果我执行 numbers["one"]
我得到“1”,但它不适用于数组,对于之前的代码我得到:
元素隐式具有“任意”类型,因为类型的表达式 'string' 不能用于索引类型。
我想使用字典中的字符串数组作为键,但我不知道该怎么做。
感谢您的帮助。
我找到了解决方案刚刚添加到我的代码 : Record
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的评论中,您注意到您收到以下错误消息
由于数组的类型,
each
的类型为string.这意味着“任何可能的字符串值”。所以它可以是“一”或“二”,但也可以是“”或“BorisJohnson”或“Fish”。
这提出了一个问题,因为您使用该值来索引仅具有键“一”、“二”或“三”的对象文字。
有两种方法可以处理这个问题,第一种是为原始对象文字提供 索引签名
但是,这是有问题的,因为在数组包含不在对象中的值的情况下,从映射返回的数组将键入
string[]
,而实际上它应该是(字符串| undefined)[]
(因为undefined
是当您使用实际上未包含在对象中的键索引对象时得到的结果)。我的首选解决方案是为您的数组提供更严格的类型:
这是一种更聪明的方法,因为如果您尝试将原本不是对象键的内容放入该数组中,编译器将抛出错误。由于此编译器错误,您的
each
变量现在保证是numbers
的键之一,因此将输入"one" | “两个”| “三”。
因此,每当您使用其中一个键对数字进行索引时,您只会得到一个字符串,因此您的数组将被正确键入,这是有道理的。
In your comment, you've noted that you are getting the following error message
Because of the type of your array,
each
is typed asstring
. 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
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)[]
(becauseundefined
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:
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 ofnumbers
, 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.