Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why typescript complains object's key is undefined even if the previous command sets a value to that key?

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 ?

enter image description here

Check example here

like image 200
but-why Avatar asked Oct 27 '25 12:10

but-why


1 Answers

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

like image 106
zixiCat Avatar answered Oct 29 '25 02:10

zixiCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!