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.
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
let x: string[] = [];
let x: string[] | undefined;
let x: string[];
if (Math.random() > .5) {
x = ['x'];
} else {
x = [];
}
return x.map(v => v);