Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Variable being used before assigned – isn't that correct?

Why is the following code invalid in strict mode:

let x: string[];
if (Math.random() > .5){ x = ['x']; }

//TS2454: x possible undefined. Yeah, I know?
return x?.map(v => v);

Yeah, I know that x may be undefined. But that’s why I’m using the Optional Chaining Operator. And that sure perfectly works on undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code is invalid in strict mode because TypeScript’s strict mode includes the strictNullChecks option, which ensures that variables cannot be used before they are assigned.

In your code, x is declared but not necessarily initialized before it is used in the return statement.

You have then 3 options

  1. Initialize x with a default value
let x: string[] = [];
  1. Use a Type Union with undefined
let x: string[] | undefined;
  1. Add an Else Case to Initialize x
let x: string[];
if (Math.random() > .5) {
   x = ['x'];
} else {
   x = [];
}

return x.map(v => v);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading