初始空对象的 TypeScript 类型
2021-03-16
168
我在使用 TypeScript 时遇到了问题,该代码在普通 JS 上运行良好
我从 TypeScript 中收到此错误:
`Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'`
const data = [{
Department: 'HR',
Name: 'Tom'
},{
Department: 'Finance',
Name: 'Peter'
},{
Department: 'HR',
Name: 'Jane'
}]
const groups = {}
for (const { Name, Department } of data) {
if (!groups[Department]) groups[Department] = { title: Department, people: [] }
groups[Department].people.push(Name)
}
console.log(Object.values(groups))
.as-console-wrapper { max-height: 100% !important; top: 0; }
我尝试添加 Props
type Props = {
title?: string
people?: string[]
}
const groups: Props | undefined = {}
但我仍然收到类似的错误
`Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Props'.`
1个回答
尝试一下:
type Department = { [name: string]: { title: string; people: string[] } };
const groups: Department = {};
Ben Wainwright
2021-03-16