Skip to content

Type guards drop string index types from the narrowed type #15388

Closed
@dherman

Description

@dherman

I'm not sure if this is related to or even a duplicate of #14957. I was attempting to define an unknown type similar to the one described in #10715, with a predicate for testing the object case that narrows the type to a dictionary type, and ran into this issue. I'm including a more minified test case below.

I could easily believe that this isn't a bug but some misunderstanding on my part -- my apologies if so. It doesn't seem like it should be a problem with subtyping; AFAICT {[key: string]: number} is a subtype of {}, right?

TypeScript Version: 2.2.2 with all strict checks turned on

Code

type NumberDict = {[key: string]: number};
type NullableObject = {} | null;

function nullableObjectIsNumberDict(x: NullableObject): x is NumberDict {
    // bogus logic; the point of this example is just the types
    return !!x;
}

function use(x: NullableObject) {
    if (!nullableObjectIsNumberDict(x)) {
        return;
    }
    x // I expected NumberDict; TS says {}
}

Expected behavior:

The narrowed type of x should be NumberDict.

Actual behavior:

The narrowed type of x is {}.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions