Remember that when you code in TypeScript, it ultimately gets converted to JavaScript and executed during runtime.
This means that you lose the strong typing benefits of TypeScript at runtime.
JavaScript will attempt to access a non-existing property like this.c
, creating it on the fly if it doesn't exist, resulting in a value of undefined
.
To mitigate this issue during compile time, using a linter such as TSLint or ESLint configured for TypeScript can help enforce variable declarations before usage (e.g. "no-use-before-declare").
This approach should catch most scenarios.
Dealing with generic cases can be more complex.
You may need to check against undefined
. In cases where an uninitialized variable is acceptable, consider initializing it with null
to distinguish between "non-existent" and "exists but not initialized."
Hopefully, this information provides some assistance.
Update:
Apologies for any confusion earlier.
In addition to Linter rules, adjusting settings in the tsconfig file can also be beneficial.
noImplicitAny - enforces type annotations
noUncheckedIndexedAccess - raises requirements for index-based access