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 Interface Index Signature

I have the following interface:

interface ClassSchedule {
  [key: string]: string;
}

However, I am receiving an error that my key is possibly undefined. How do I account for this?

interface ClassSchedule {
  [key: string]: string;
}

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 :

It sounds like you have the --noUncheckedIndexedAccess compiler option enabled.

You can avoid this error by:

  • Disabling that compiler option (though that loses you a bit of type safety).
  • Checking whether the key exists before trying to access it (e.g. by wrapping the access in an if statement).
  • Adding an ! after the key (e.g. foo.bar! or `foo["bar"]!) to assert that the value will always be non-null.
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