type MaybeThereIsAValue = {
[p: string]: string | undefined
}
...
let bar: MaybeThereIsAValue = {};
const key = "carpe";
bar[key] = "diem";
const why = bar[key];
// why is string | undefined
Why is why string | undefined since I am literally assigning a value to bar[key] in the previous line ?
How can I avoid it ?

Check example here
I got why it would get that.
That is because strictNullChecks of tsconfig is set to be true, which default is false,
and const key = 'carpe' is only executed after the TS is compiled into JS, so TS doesn't know which key it is.
strictNullChecks: When type checking, take into account null and undefined.
So if you want to solve that, my two solutions are:
1. set the strictNullChecks of tsconfig to be false
2. Use ! non-null assertion operator
const why = bar[key]!;
Let's think about this situation:
let key = 'carpe';
bar[key] = 'diem';
// the next line would only be executed after the TS is compiled into JS.
key = 'test';
// that is to say TS does not know the key is 'test' or 'carpe'
// so `why` is type of string or undefined
const why = bar[key];
If you set strictNullChecks to be false, why will always be type of string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With