Skip to content

Typescript loses refinement information when overwriting a local variable with its same type #36579

Closed
@EdwardDrapkin

Description

@EdwardDrapkin

When you refine a variable with a user defined type guard, and then reassign that variable to the result of a function returning the same type, TS loses track of the refined type.

Search Terms:
refinement

Code

interface A { _a: true } 

const isA = (item: any): item is A => true;

declare const foo: any;

function example<T extends {}>(input: T): T { 
    return input;
}

function exampleUsage<T extends {}>(item: T) {
    if (isA(item)) {
        // works
        console.log(item._a);
    }

    item = example(item);

    if (isA(item)) {
        // works
        console.log(item._a);
    }

    if (isA(item)) {
        item = example(item);
        console.log(item._a);
    }
}

Expected behavior:
In the final case, because the function example returns the same type as it was provided, TS should keep track of item's refined type.

Actual behavior:
TS loses track of the fact that item has previously been refined to an instance of A.

Playground Link: http://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgILIN7IPpwFzJhQCuKAvsgFCUID2IAzmMsA+gLzIAUwkAtgTggAngEoCvCHxYM0ydgD5CJCAG5qAEwgIANnCgo6jZjFq1BI9ZRjEQCMMHrIIADzh8ADjogAeACrOLpAgGrIYZAo8IB7EYAR+4sgBWJTIacgGYMRQICzRsepk1DZ2Dk6u7l4QAKoMcADmvgGuwaGYETz88aKYqenAMNysqJ1Soj0YfenpAPQzyADutFAA1gxT08hGDLTeAHQ6tPWjfHu4ourTRRuS0pwVnt4nF9TTA0NszxMb03OLy2sfultrsIAcjicznAXldXv1BjxPrdxr1Nv1+PJApUnsjLmitvQdvtDsdblCYekimQgA

Related Issues: n/a

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