If you want to easily catch errors of this type, consider turning on TypeScript's strict
mode or enabling the noImplicitAny
flag in your tsconfig.json
configuration file.
Once one of these options is activated, you will receive an error message similar to the following:
wat.ts:2:1 - error TS7017: Element implicitly has an 'any' type because type '{ someKey: string; }' has no index signature.
foo['NonExistentKey'].bar.baz
In the absence of these flags, the variable foo
is automatically typed as
const foo: { [index: string]: any, someKey: string }
. This decision is based on the fact that JavaScript developers often access properties of objects using arbitrary indexes without defining explicit types, which may not be a safe practice in terms of type-checking.
Personally, I find the behavior allowed by non-strict mode to be confusing and potentially error-prone. Therefore, I recommend setting strict: true
in your tsconfig.json
file for better code quality and safety.
You can refer to the full documentation on TypeScript compiler options here.
For more information about tsconfig.json
configurations, visit this link.
Additional details on index signatures in TypeScript can be found here.