Closed
Description
TypeScript Version: 3.1.0-dev.20180920
Search Terms: strictNullChecks
Code
This might seem weird, but is based on actual real-world code.
declare function baz(): Promise<true | "a" | "b" | "c" | Error>;
async function foo() {
let bar: "x" | Error;
for (let i = 0; i < 3; i++) {
const test = await baz();
switch (test) {
case true: return;
case "a": throw new Error("a");
case "b": {
bar = "x";
continue;
}
default: {
if (test instanceof Error) {
bar = new Error("foo");
continue;
} else {
throw new Error("c");
}
}
}
}
// false positive: bar is used before being assigned
if (bar === "x") {
} else {
bar.message = "something";
}
}
Expected behavior:
No error after the for loop. The only way to get there is if bar
has the value "x"
or is an instance of Error
. If baz
resolves to true
, the function returns, "b"
sets bar
to "x", and "a"
and everything that is not an Error (including "c"
throw, and an Error sets it to an Error.
Actual behavior:
Variable "bar"
is used before being assigned.
Related Issues: #24091