- 
                Notifications
    You must be signed in to change notification settings 
- Fork 13.1k
Closed as not planned
Closed as not planned
Copy link
Labels
Not a DefectThis behavior is one of several equally-correct optionsThis behavior is one of several equally-correct options
Description
π Search Terms
asserting type
as changing underlying type
π Version & Regression Information
- This changed between versions v4.2 and v4.3
β― Playground Link
π» 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".

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
Labels
Not a DefectThis behavior is one of several equally-correct optionsThis behavior is one of several equally-correct options