Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Const typeguard flows into methods but not properties #45006

Closed
jods4 opened this issue Jul 13, 2021 · 2 comments Β· Fixed by #45020
Closed

Const typeguard flows into methods but not properties #45006

jods4 opened this issue Jul 13, 2021 · 2 comments Β· Fixed by #45020
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@jods4
Copy link

jods4 commented Jul 13, 2021

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.

@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Jul 13, 2021
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Jul 13, 2021
@softwareCobbler
Copy link
Contributor

softwareCobbler commented Jul 14, 2021

should control flow flow into setters, too?

@jods4
Copy link
Author

jods4 commented Jul 14, 2021

@softwareCobbler Yes.

const x: string | null = "abc";
if (x) {
 const obj = {
    // Following is valid and should not warn that x might be null
    set test(val) { console.log(x.toUpperCase(); }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants