4
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

2
  • Why I can't get the type string | undefined, my why is type of 'string' Commented Apr 3, 2021 at 10:27
  • @zixiCat Don't know. When I hover my mouse over the why, my IDE says it's string | undefined, check the attached image I just uploaded Commented Apr 3, 2021 at 10:29

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

I get it to work with the ! at the end but could you elaborate more ? I mean why the distinction between null and undefined would cause such an issue since I explicitly declare it as string | undefined and not string | null | undefined ?
there no diff between them, strictNullChecks just let it consider the type of this object if contains null or undefined, if you set ____________________________________________________________________________________ type MaybeThereIsAValue = { [p: string]: string | undefined | null; }; ____________________________________________________________________________________ perhaps why is type of string | undefined | null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.