Inamul Hassan
Inamul Hassan

Reputation: 148

Update an typescript object

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)

Upvotes: 0

Views: 14849

Answers (1)

leonardfactory
leonardfactory

Reputation: 3501

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.

Upvotes: 6

Related Questions