Skip to content

Asserting changes type of original variable inline (the change reverts in subsequent lines)Β #58055

Closed as not planned
@paradoxloop

Description

@paradoxloop

πŸ”Ž Search Terms

asserting type
as changing underlying type

πŸ•— Version & Regression Information

  • This changed between versions v4.2 and v4.3

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.3#code/MYewdgzgLgBAHjAvDA3gWAFAxgcgJ44BcuAFgKYA2FIOANJtjnETAIwAMmAvppgGYBXMMCgBLcDAggAtmQBiQkeLAAeACowycKGTAATCDADWZPCD4woeAA5lz8AHwAKawCcQ1wmoCUqBpIB3UShgEhgXd2tfdCxsGGAAQwgyXAJCfziYAHosmATYKBJRQ2sQUTBYNw8YYskxKhgAIjxGmAAfJrhWvQEUqBBLGzIIYFdRa1gwEFgAIzJygHM8mYo+gbAE13cAjLiczQgKcthXAVWmqYBaITJgYYhNvEurW0uk5NcxcFa3MgA3XRQQwbLYgIJgJYgASuZIUAEQXbYUCQE6sJAwKrWADciOyuUymQAegB+XHI6AwVwAJnRmLyhnwOBxsUy+wJcRJuJmrjICSMzOwPAw3EwQA

πŸ’» Code

const x = {
  'y': 'hello',
  'x': 10
}

function someFunction<T extends keyof typeof x>(prop:T) {
  switch (prop) {
    case 'y':
      // at this point prop is still "y" | "x" due to typescript not being able to narrow
      // eslint rule "no-unecessary-type-assertion" prevents narrowing ourselves
      const r1 = prop;
      //         ^?
      const r2 = prop as 'y';
      //         ^?
      break;
  }

}

πŸ™ Actual behavior

If you inspect the types of prop with and without the assertion you can see that without the assertion TS reports the type of prop to be T extends "y" | "x" but with the assertion TS reports the type of prop as "y".
image

This is a bug with TS itself - a behaviour changed in TS v4.3. In v4.2 TS correctly reports both locations as the generic - in v4.3+ it exhibits the above behaviour.

πŸ™‚ Expected behavior

The assertion should not be changing the type of the original variable.

Additional information about the issue

Discovered while debugging a eslint issue .

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions