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

Typescript: for .. in – define variable as keyof instead of string

When I iterate over keys in TypeScript the variable is being assigned the type of string instead of type keyof object that I enumerate.

Example:

class Files {
  patches?: Data;
  website?: Data;
  github?: Data;
}

const files: Files = {};

for (const file in Files.prototype) {
  if (files[file]) {
    console.log(files[file])
  }
}

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

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

How can I solve this?

>Solution :

You can declare the file outside of the for in with the correct type:

const files: Files = {};

let file: keyof typeof Files.prototype;

for (file in Files.prototype) {
  if (files[file]) {
    console.log(files[file]);
  }
}
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