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

Typescript checking fails when ternary operator logic is extracted #48146

Closed
ArthurMbraga opened this issue Mar 7, 2022 · 1 comment
Closed

Comments

@ArthurMbraga
Copy link

Bug Report

πŸ”Ž Search Terms

  • ternary operator problem
  • shallow type check
  • extracted ternary operator condition problem

πŸ•— Version & Regression Information

  • V4.6.2

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function example1(obj: { value?: number }) {
    const showValue = typeof obj.value === "number";

    showValue ? print(obj.value) : hide()
}

function example2(obj: { value?: number }) {
    typeof obj.value === "number" ? print(obj.value) : hide()
}

function print(num: number) { console.log(num) }
function hide() { }

πŸ™ Actual behavior

Only at example1() I'm getting this error:

Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.

but the argument will never be undefined

image

πŸ™‚ Expected behavior

Is expected that both example1() and example2() functions compile, because, technically, they are the same

@equt
Copy link

equt commented Mar 7, 2022

Marking the value as readonly will make example 1 work. And the reason has been explained in the corresponding fix PR here, which in brief is

...

We'd effectively have to check that there are no assignments to obj.data between the declaration of isString and the reference to isString in the if statement. This adds complexity and could be prohibitively expensive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants