[英]TypeScript type for initial empty object
I am having problems with TypeScript on this code which works well on normal JS我在此代码上遇到 TypeScript 问题,该代码在普通 JS 上运行良好
I get this error form TypeScript:我从 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; }
I have tried to add the Props我试图添加道具
type Props = {
title?: string
people?: string[]
}
const groups: Props | undefined = {}
But I still get a similar error但我仍然收到类似的错误
`Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Props'.`
Try this:尝试这个:
type Department = { [name: string]: { title: string; people: string[] } };
const groups: Department = {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.