Errors issued for working code due to narrowing behaviour #7160
Closed
Description
opened on Feb 20, 2016
TypeScript Version:
nightly (1.9.0-dev.20160217)
Code
interface Thing { thing: string; }
function isThing(x: any): x is Thing {
return x && typeof x.thing === 'string';
}
function foo(x: Thing|string) {
let branch: number;
let result: string;
if (typeof x === "string") {
branch = 1;
result = x; // OK
if (isThing(x)) {
branch = 2;
result = x.thing; // ERROR: 'thing' does not exist on type 'string'
}
}
else {
branch = 3;
result = x.thing; // OK
if (typeof x === "string") {
branch = 4;
result = x // ERROR: 'Thing|string' is not assignable to type 'string'
}
}
return `(${branch}) ${result}`;
}
let a = foo('string a');
let b = foo({thing: 'thing b'});
String.prototype['thing'] = 'thing c';
let c = foo('string c');
console.log(a, b, c); // outputs "(1) string a (3) thing b (2) thing c"
Expected behavior:
No compile-time or runtime errors, and outputs "(1) string a (3) thing b (2) thing c"
Actual behavior:
No runtime errors, and outputs "(1) string a (3) thing b (2) thing c"
as expected, but compiler issues two errors as shown in code comments.
Metadata
Assignees
Labels
No labels
Activity