Skip to content

Typescript checking fails when ternary operator logic is extractedΒ #48146

Closed
@ArthurMbraga

Description

@ArthurMbraga

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