Skip to content

typeof operator not using undefined guard in when used in a loop nested in the guardΒ #43411

Closed
@lesiak

Description

@lesiak

Bug Report

πŸ”Ž Search Terms

typeof, type guard, undefined guard, loop

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type System Behaviour and Type Guards

⏯ Playground Link

Playground link

πŸ’» Code

interface IProperties {
    foo?: {
        aaa: string
        bbb: string
    }
}

function init(properties: IProperties) {
    if (properties.foo) {
        type FooOK = typeof properties.foo;  
        properties.foo; // type is { aaa: string; bbb: string; }
        for (const x of [1, 2, 3]) {
          properties.foo; // type is { aaa: string; bbb: string; }
          type FooOrUndefined = typeof properties.foo; //type is { aaa: string; bbb: string; } | undefined
        }
    } 
}

πŸ™ Actual behavior

Under a loop nested in undefined type guard for variable properties.foo,

  • properties.foo is inferred to be { aaa: string; bbb: string; }
  • typeof properties.foo is inferred to { aaa: string; bbb: string; } | undefined
    This happens both for for...of and while loops.

πŸ™‚ Expected behavior

typeof takes type guard into account:

  • typeof properties.foo is inferred to { aaa: string; bbb: string; }

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions