I have a TypeScript codebase (v4.7.3) with "strict": true enabled is my tsconfig, and I have code like the following (basically, a hashmap where some keys may exist and others not):
// Cache promises in a hashmap, where the key is some unique identifier, and
// the value is a Promise object
const promiseCache: { [key: string]: Promise<void> } = {};
// I expect TypeScript to flag the below expression as possibly being undefined
// and require me to wrap the below line in an `if` statement to ensure the
// promise at the specified key actually exists
promiseCache['4c8e17ce-9ca5-457a-925e-a8c36fe90508'].then(() => {
console.log('then!');
});
Obviously, the above code is simplified to demonstrate the problem, but the nature of what I'm doing is the same: a hashmap that starts out empty, and a square-bracket key lookup to look up the value dynamically.
I have gathered that { [key: string]: ... } is the generally-correct way to define objects with dynamic keys. However, I expect this construct to abide by the other rules of TypeScript - namely, that
I have searched Google and StackOverflow the best I can, and have not been able to find any issues that are remotely similar. My issue is trying to understand why TypeScript is not showing an "... is possibly undefined" type of error.
What can I do to enforce the strict null/undefined checking for my code above?