I understand the reasoning behind that.
The reason is because the strictNullChecks setting in tsconfig is set to true by default, even though its default value is false,
Also, the line const key = 'carpe'
gets executed only after TypeScript is compiled into JavaScript, causing TypeScript to be unaware of which key it refers to.
strictNullChecks: Considers null and undefined during type checking.
To address this issue, I suggest two solutions:
1. Change the strictNullChecks
setting in tsconfig
to false
2. Utilize the !
operator from non-null assertion operator
const why = bar[key]!;
Consider this scenario:
let key = 'carpe';
bar[key] = 'diem';
// The following line will only run after TS is compiled into JS.
key = 'test';
// Therefore, TS cannot determine if the key is 'test' or 'carpe'
// Hence, `why` can be of type string or undefined
const why = bar[key];
If you disable strictNullChecks, why
will consistently remain a string type.