0

I am having problems with TypeScript on this code which works well on normal JS

I get this error form 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'.`
3
  • 2
    groups: { [key: string]: { title: string, people: string[] } } = {}; typescriptlang.org/play?#code/… Commented Mar 16, 2021 at 16:06
  • 1
    Thanks it also worked with const groups: { [key: string]: Props } = {} Commented Mar 16, 2021 at 16:10
  • There is a utility type Record<Keys, Values> which is a shorthand for the “[key: string]:” index. You can use Record<string, Props> if that’s more readable. Functionally it’s the same. It means an object whose keys are type string and whose values are type Props. Also I would make the properties on Props required rather than optional. Commented Mar 16, 2021 at 17:11

1 Answer 1

2

Try this:

type Department = { [name: string]: { title: string; people: string[] } };

const groups: Department = {};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.