Skip to content

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

Closed

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

Activity

  1. equt commented on Mar 7, 2022

    @equt

    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.

  2. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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