Quick1: Typescript

I’ve been using Typescript for 12 months and every now and then I get blocked. I used to do a fair bit of ‘typescript ignore’ in my code just to keep things moving and depend on my tests to throw up mistakes.

This I think ha caught me out a few times in different circumstances.

interface Options {
  id: string;
  name: string;
}
const options: Options = {id: "qwerty", name: "andy pandy"}

Object(options).forEach(key => {
  localOptions[key] = options[key]
});

The above would not compile and give the following message (note if I set the line to be ignored the code still worked)

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘xxxx’. No index signature with a parameter of type ‘string’ was found on type ‘xxxx’

So how to comply with Typescript?

I found two options. One went about extending the object constructor and adding overloads the second is type-casting. Extending the object constructor is probably more “correct” but type-casting worked and when you read the code it simpler to understand (IMHO)

interface Options {
  id: string;
  name: string;
}
const options: Options = {id: "qwerty", name: "andy pandy"}

Object(options).forEach(key => {
  localOptions[key as keyof Options] = options[key as keyof Options]
});

Does it work and does it address the issue? Yes it does.