1

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'.

How can I solve this?

1
  • There are many Q&A on that error message. Please check. For instance this answer to use keyof type assertion. Commented Aug 2, 2023 at 17:22

1 Answer 1

2

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]);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the answer. Is there any other option, if I want to define file variable inside the for parameters?
If you want to go without the assertion then I don't think there is any other way to do it with for in

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.