Skip to content

Typescript checking fails when ternary operator logic is extracted #48146

Description

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions