Skip to content

User-defined type guards seemingly unused when given an intersection type #10144

Closed
@TyOverby

Description

@TyOverby

TypeScript Version: 1.8.10

Code

interface Foo {
    x: number;
    s: string;
}

interface Bar {
    y: number;
    z: number;
}

interface HasNum {
    a: number;
}

type FooOrBar = Foo | Bar;

type FooOrBarWithNum = FooOrBar & HasNum;

function is_foo(f: FooOrBar): f is Foo {
    return (f as Foo).x !== undefined;
}

let obj: FooOrBarWithNum = {
    a: 5,
    x: 5,
    s: "hello"
};

if (is_foo(obj)) {
    obj.x; // ERROR: Property 'x' does not exist on type (Foo | Bar) & HasNum
}

let obj_2: FooOrBar = obj; // Cast it back to just a FooOrBar.

if (is_foo(obj_2)) {
    obj_2.x; // This compiles just fine.
}

Expected behavior:
I would expect obj to have type Foo inside of the if-block.

Actual behavior:
obj is not refined, but obj_2 is.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions