Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Interface Index Signature

Tags:

typescript

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;
}
like image 491
Ryan Thomas Avatar asked Nov 30 '25 16:11

Ryan Thomas


1 Answers

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.
like image 133
Joe Clay Avatar answered Dec 04 '25 00:12

Joe Clay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!