映射数组以访问 TypeScript 中的字典值
Map an array to access dictionary values in TypeScript
我正在学习,所以我有下一个代码...
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr= ["one","one","two","one","three"]
arr.map((each)=>numbers[each])
如果我这样做 numbers["one"]
我得到“1”,但它不适用于数组,对于前面的代码我得到:
Element implicitly has an 'any' type because expression of type
'string' can't be used to index type.
我想使用字典中的字符串数组作为键,但我不知道该怎么做。
感谢您的帮助。
我发现 刚刚添加到我的代码中 : Record<string, any>
在您的评论中,您注意到您收到了以下错误消息
"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type"
由于数组的类型,each
被键入为 string
。这意味着“任何可能的字符串值”。所以它可以是“一个”或“两个”,但也可以是“”或“BorisJohnson”或“Fish”。
这会带来问题,因为您已经使用该值来索引对象文字,而该对象文字只有键“一”、“二”或“三”。
有两种方法可以解决这个问题,第一种是给你的原始对象文字一个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])
但是,这是有问题的,因为在您的数组包含不在对象中的值的情况下,从您的地图返回的数组将被键入 string[]
,而实际上它应该是 (string | undefined)[]
(因为 undefined
是您使用实际上不包含在对象中的键索引对象时得到的结果)。
我的首选解决方案是为您的数组提供更严格的类型:
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr: (keyof typeof numbers)[] = ["one", "one", "two", "one", "three"]
arr.map((each) => numbers[each])
这是一种更聪明的方法,因为如果您尝试将原本不是对象键的内容放入该数组,编译器将抛出错误。由于此编译器错误,您的 each
变量现在保证是 numbers
的键之一,因此将键入 "one" | "two" | "three"
.
因此,每当您使用其中一个键对 numbers
进行索引时,您只会得到一个字符串,因此您的数组将被正确键入。
我正在学习,所以我有下一个代码...
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr= ["one","one","two","one","three"]
arr.map((each)=>numbers[each])
如果我这样做 numbers["one"]
我得到“1”,但它不适用于数组,对于前面的代码我得到:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type.
我想使用字典中的字符串数组作为键,但我不知道该怎么做。
感谢您的帮助。
我发现 : Record<string, any>
在您的评论中,您注意到您收到了以下错误消息
"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type"
由于数组的类型,each
被键入为 string
。这意味着“任何可能的字符串值”。所以它可以是“一个”或“两个”,但也可以是“”或“BorisJohnson”或“Fish”。
这会带来问题,因为您已经使用该值来索引对象文字,而该对象文字只有键“一”、“二”或“三”。
有两种方法可以解决这个问题,第一种是给你的原始对象文字一个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])
但是,这是有问题的,因为在您的数组包含不在对象中的值的情况下,从您的地图返回的数组将被键入 string[]
,而实际上它应该是 (string | undefined)[]
(因为 undefined
是您使用实际上不包含在对象中的键索引对象时得到的结果)。
我的首选解决方案是为您的数组提供更严格的类型:
const numbers = {
one: "1",
two: "2",
three: "3"
}
const arr: (keyof typeof numbers)[] = ["one", "one", "two", "one", "three"]
arr.map((each) => numbers[each])
这是一种更聪明的方法,因为如果您尝试将原本不是对象键的内容放入该数组,编译器将抛出错误。由于此编译器错误,您的 each
变量现在保证是 numbers
的键之一,因此将键入 "one" | "two" | "three"
.
因此,每当您使用其中一个键对 numbers
进行索引时,您只会得到一个字符串,因此您的数组将被正确键入。