-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
if
statement in loop changes type of variable outside the if
#19955
Comments
Duplicate of #18840. |
Actually, I'll flip it back to a bug since it is not exactly the same as #18840. However the root cause is similar: A narrowing by a discriminant property (such as |
Another case: function containsItself(arr: {}): boolean {
if (!Array.isArray(arr)) {
return false;
}
for (const x of arr) {
if (x === arr) {
return true;
}
}
return false;
}
And another: function f(u: { type: "A"; x: number; } | { type: "B"; x?: number; }) {
if (u.type === "A") {
u.x; //number
}
if (u.type === "B" && u.x !== undefined) {
u.x; //number
}
if (u.type === "A" || u.type === "B" && u.x !== undefined) {
u.x; // number | undefined
}
} |
A possibly related error: interface Base { a: number | string; }
interface A extends Base { kind: "A"; }
interface B extends Base { kind: "B"; }
function f(x: A | B): void {
if (typeof x.a === "number") {
if (x.kind === "A") { } // No error if this is removed
const n: number = x.a; // Error
}
} |
Another case: function f(a: number | undefined) {
if (!a) return;
for (const b of [a]) {
if (b === a) {}
}
}
|
Another case from #26673: interface A {
isA: true;
m?(): void;
}
interface B {
isA: false;
m?(): void;
}
class User {
p!: A | B;
go(): void {
if (this.p.m) {
if (this.p.isA) {}
this.p.m(); // No error (good)
}
const p = this.p;
if (p.m) {
if (p.isA) {}
p.m(); // Error (bad)
}
}
} |
This looks to be fixed by #32695; specifically, the cases involving loops. |
Indeed it is. Thanks for noticing! |
TypeScript Version: 2.7.0-dev.20171112
Code
Expected behavior:
No error.
Actual behavior:
src/a.ts(4,19): error TS2532: Object is possibly 'undefined'.
The text was updated successfully, but these errors were encountered: