You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * Those returns should not be errors */consttestFn=<Textendsstring|number>(val: T): T=>{if(typeofval==="number"){return3;}return"3";}/** * I shouldn't have to cast the returns to T */consttestFn2=<Textendsstring|number>(val: T): T=>{if(typeofval==="number"){return3asT;}return"3"asT;}constsomeNumber=testFn(3);constsomeString=testFn("3");
🙁 Actual behavior
Error in both returns of testFn even though they both are ok according to the T generic. someNumber is corectly infered as number, someString is correctly inferred as string and error properly throws an error because the argument doesnt follow the constraints of the generic T
I can correct this by casting the returns to T but it seems like it should not be necessary. It feels like a workaround.
🙂 Expected behavior
No errors in the testFn returns.
The text was updated successfully, but these errors were encountered:
Even without the re-constraining of T this would fail, because testFn(0) returns a value of type 0, but you're actually returning 3. So ["oops"][testFn(0)].toUpperCase(); compiles but throws a runtime error. So the example here would need to be improved before it would even be a duplicate of #33014.
Bug Report
I think typescript should be able to correclty infer the type of a generic if a primary type check is made inside a function.
🔎 Search Terms
Different subtype of constraint
Primary type
🕗 Version & Regression Information
This happens in the newest version of typescript
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
Error in both returns of
testFn
even though they both are ok according to the T generic.someNumber
is corectly infered as number,someString
is correctly inferred as string anderror
properly throws an error because the argument doesnt follow the constraints of the genericT
I can correct this by casting the returns to T but it seems like it should not be necessary. It feels like a workaround.
🙂 Expected behavior
No errors in the testFn returns.
The text was updated successfully, but these errors were encountered: