Skip to content

Const typeguard flows into methods but not propertiesΒ #45006

@jods4

Description

@jods4

Bug Report

πŸ”Ž Search Terms

type guard get property const

πŸ•— Version & Regression Information

Fails at least on 4.3.5 and 4.4.0-beta.

  • I was unable to test this on prior versions because I noticed this behavior very recently.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const x: string | number = Math.random() < 0.5 ? "str" : 123;
if (typeof x === "string") {
  let obj = {
    get prop() { return x.toUpperCase() },  // Error: property toUpperCase doesn't exist on number
    method() { return x.toUpperCase() } // Ok
  }
}

πŸ™ Actual behavior

The method compiles, the getter raises an error.

πŸ™‚ Expected behavior

Behaviour should be the same for both.
Given that x is a const and its type was narrowed to string, no error seems right.

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