Kokizzu
Kokizzu

Reputation: 26848

TypeScript update object inplace

How to correctly write this in Typescript?

var obj = {
  kv: {
    foo: 'bar',
    bar: 'baz'
  }
};

for(const k in obj.kv) {
  const v = obj.kv[k];
  obj.kv[k] = 'prefix' + v; 
  // error TS7017: Index signature of object type implicitly has an 'any' type.
}

// desired output:
// { kv: { foo: 'prefixbar', bar: 'prefixbaz' } }

I want to update each item on the obj.kv object.

Upvotes: 0

Views: 1675

Answers (3)

Aluan Haddad
Aluan Haddad

Reputation: 31823

const obj = {
  kv: {
    foo: 'bar',
    bar: 'baz'
  }
};

Object.entries(obj.kv).forEach(([key, value]) => {
  obj.kv[key] = `prefix${value}`; 
});

Note that the entries method was added in ECMAScript 2016. If you do not have it available, natively or via a polyfill, you can write

Object.entries(obj.kv)
  .map(key => [key, obj.kv[key]])
  .forEach(([key, value]) => {
    obj.kv[key] = `prefix${value}`; 
  });

instead.

Upvotes: 2

ntabee
ntabee

Reputation: 436

While a bit verbose, this would be more type-friendly:

var obj = {
  kv: {
    foo: 'bar',
    bar: 'baz'
  } as {
      [key:string]: string,
  }
};

for (const k of Object.keys(obj.kv)) {
  const v = obj.kv[k];

  // error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
  // const erroneous = Math.round(v);  

  obj.kv[k] = 'prefix' + v; 
}

Upvotes: 1

Amid
Amid

Reputation: 22352

You can refactor it this way:

var obj = {
  kv: {
    foo: 'bar',
    bar: 'baz'
  }
};

for (const k of Object.keys(obj.kv))
{
  const v = (obj.kv as any)[k];
  (obj.kv as any)[k] = 'prefix' + v;
}

Upvotes: 2

Related Questions