0

We can all see that this code is valid javascript:

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

['foo', 'bar'].forEach((key) => {
  delete myObj[key];
});

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: string; bar: number; baz: string; }'. No index signature with a parameter of type 'string' was found on type '{ foo: string; bar: number; baz: string; }'.

So what's the best way of doing this TypeScript compatible?

MrMamen
  • 359
  • 2
  • 14
  • http://www.typescriptlang.org/play/#code/MYewdgzgLgBAtgTwPICMBWMC8MDeBYAKBhgDMQQAuGAImgCcBLMAc2oBpDiUBDOqgRgBMAZg5EYPAF5VqDOAAcQdKNzCxoAVxIlqhAL4BuQoQAUAbQDkZEBbYwLPOhYC6ASgB0ZOgFFuwABYmJgDWAKYIrlgAfLicMAAmoQA2oVCh8MjoZmEIzkYEeq75QA – MrMamen Oct 23 '19 at 11:34
  • This is similar to https://stackoverflow.com/q/13315131/990642 – josephdpurcell Aug 19 '22 at 15:52

2 Answers2

1

Try typing your array :

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

const myArray: (keyof typeof myObj)[] = ['foo', 'bar']

myArray.forEach(...)
JeromeBu
  • 1,099
  • 7
  • 13
0

One workaround is:

(['foo', 'bar'] as (keyof typeof myObj)[]).forEach((key) => {
  delete myObj[key];
});

But it does not prevent typing errors in the array-strings.

MrMamen
  • 359
  • 2
  • 14