Skip to content

Local Meaning of Union Types (safe assignments)  #17188

Closed
@olegdunkan

Description

@olegdunkan

TypeScript Version: Playground

Code

class A {
    x: number;
}

class B extends A {
    y: number;
}

class C extends A {
    z: number;
}

declare function process(c:C);
function f(x:  B | C) {
    
    if (x instanceof C) {
        //we memorize x in c
        let c = x; //here x of type C        
      
        //restore x
        x = c;  //here x loses the narrowed type and x is now B | C again and is's by design    
        x.z = 1; //no error, what? 
        process(x);  //it have to be an error, what?
    }
}

Preamble:
A type guard for a variable x has no effect if the statements or expressions it guards contain assignments to x.

If compiler knows that the type of right hand expression is the same as narrowed type of parameter (in my case) why does compiler expand type of x to the initial type? Maybe it is possible to check for this type of assignments?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs More InfoThe issue still hasn't been fully clarified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions