Closed as not planned
Closed as not planned
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 .