0

When things come to Javascript updating an object is something is like following.

const data = {
    a: 1,
    b: 3,
    c: 4
}


const update = (summary) => {
  data[summary] += 1;
  console.log(data);

}

update('a');

I tried the same thing with Typescript but it doesn't work as such I know I'm doing something wrong can someone point out the faults and how to work things out.

interface Summary { 
    a: number,
    b: number,
    c: number
}

const data: Summary = {
    a: 1,
    b: 3,
    c: 4
}


const updateData = (summaryType: string) => { 
    data[summaryType] += 1 // Error
}

The Error is -> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Summary'. No index signature with a parameter of type 'string' was found on type 'Summary'.(7053)

Inamul Hassan
  • 138
  • 1
  • 2
  • 11
  • 1
    Does this answer your question? [TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type](https://stackoverflow.com/questions/57438198/typescript-element-implicitly-has-an-any-type-because-expression-of-type-st) – Victor Alessander Apr 26 '20 at 01:01

1 Answers1

6

Since you are updating an object with a specific type, TS wants to know that summaryType is a valid property name (key) for the data type. In this case, you can simply define summaryType as a key of Summary, literally:

const updateData = (summaryType: keyof Summary) => { 
    data[summaryType] += 1
}

In case you have an object literal, and not its type, you can use typeof obj to get its type, and again keyof to get the valid keys:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

const ObjType = typeof obj;

function update(type: keyof ObjectType) { // or just `keyof typeof obj`
  obj[type] += 1;
} 

If you don't know the type, or if you want to ignore the error, you can just use data[summaryType as any] even if this is not a good practice since you are introducing potential bugs in your code that the TS checker is avoiding.

leonardfactory
  • 3,353
  • 1
  • 18
  • 25