Skip to content

Errors issued for working code due to narrowing behaviour #7160

Closed
@yortus

Description

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions