我试图最终得到一本字典列表的字典,但我很难向其中添加元素。我拥有的是一个足够简单的 CSV,在 Excel 中看起来就像这样。
上面的内容是使用 papa.parse 解析为一个字典数组,标题是字典的键,但我需要以特定的方式格式化它
我最终需要的是一本字典,其第一个条目:
finalDict = {
state: "CA"
governor: {
first_name: "Gavin"
last_name: "Newsom
}
cities: [{city1: "LA", population: "8M", mayor: "ABC"},
{city2: "SF", population: "1M", mayor: "DEF"}]
}
看起来应该很简单,我编写了一个函数,它接受一个文件并迭代,但我对上面的“城市”键有困难
function parseFile(csv) {
let stateGovs = {
state: ""
governor: {
first_name:""
last_name:""
}
cities:[]
}
#Note I can write more detail in my for loop upon request, but this is where the issue is
csv.forEach((entry) =>
#insert some more parsing logic, but I end up with a temp variable that looks like
#temp = {city1: "LA", population: "8M", mayor: "ABC"} and I say
stateGovs.cities.push(temp)
}
我在字典中定义城市的方式,智能感知告诉我它的类型是 never[],当我尝试将任何内容推送到它(即我的临时字典)时,我收到警告“argument of type any[]/{ } 不能分配给“never”类型的参数”,这就是我陷入困境的地方。我尝试将我的临时变量设置为一个字典列表,在我的函数之外显式定义一个类型,但问题的关键是这个,并且似乎没有任何效果,因为我不知道(足够)我在这里做错了什么。任何帮助将不胜感激。
当您初始化空数组时,TypeScript 在
简单情况中将其隐式推断为
any[]
(请参阅 ms/TS#18687),或者在其他情况下推断为 never[]
类型(就像您的属性 stateGovs.cities: []
的情况一样) .
因此,它认为您尝试推入该数组的任何内容都是不正确的,因为没有任何内容可以分配给
never
。
在许多情况下,我们计划稍后填充空数组。只需告诉 TypeScript 数组应该包含什么:
interface City {
city1: string
population: string
mayor: string
}
const cities: City[] = []
const cities2: Array<City> = [] // Alternative syntax
const cities3 = [] as City[] // Type assertion
另请参阅https://www.geeksforgeeks.org/how-to-avoid-inferring-empty-array-in-typescript/
在你的情况下,你可以简单地这样做:
const stateGovs2 = {
state: "",
governor: {
first_name: "",
last_name: ""
},
cities: [] as City[] // Type assertion
}
...现在 TypeScript 可以让您推入符合
City
接口的数组对象:
stateGovs2.cities.push(temp) // Okay
// ^? City[]