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.
>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
- Initialize x with a default value
let x: string[] = [];
- Use a Type Union with undefined
let x: string[] | undefined;
- Add an Else Case to Initialize x
let x: string[];
if (Math.random() > .5) {
x = ['x'];
} else {
x = [];
}
return x.map(v => v);