Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to 'index type' using a string variable

I’m trying to invert an object’s fields if a value exists, but I’m getting some error that I cannot decipher.

interface Control {
  name1: boolean;
  name2: boolean;
  ...
}

const values = ['name1', 'name2', ...];

const control: Control = {
  name1: false,
  name2: false,
  ...
}

for (const value of values) {
  if ((value in control) {
    control[value] = !control[value];  // error
  }
}

Error message:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Control'.
  No index signature with a parameter of type 'string' was found on type 'Control'.ts(7053)

However, the error goes away if I explicitly pass one of the object’s fields, such as control['name1'].
Is there something I am not understanding?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

TypeScript doesn’t know that your values array is an array of specific strings, only that it’s a string[]. Try this:

interface Control {
  name1: boolean;
  name2: boolean;
}

const values = ['name1', 'name2'] as const;

const control: Control = {
  name1: false,
  name2: false,
}

for (const value of values) {
  if (value in control) {
    control[value] = !control[value];  // error
  }
}

TypeScript Playground

That as const tells TypeScript to specify the type of values more tightly to be ['name1', 'name2'] in this case, so when you’re iterating through it value will be typed as 'name1' | 'name2' and TypeScript will understand that those values can be used to index a Control.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading