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;
}
>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
ifstatement). - Adding an
!after the key (e.g.foo.bar!or `foo["bar"]!) to assert that the value will always be non-null.