-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Conditionnal return type not recognized inside the function #59618
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Duplicate of #33912. |
Solution You can resolve this by using type assertions or by separating the logic into distinct functions. Here's a solution using type assertions: typescript
In the code above:
Explanation
Alternatively, you can split the logic into two functions, which can be more type-safe: typescript
This way, the type logic is handled separately, and TypeScript is less likely to encounter problems with narrowing.
|
Looks like a garbage ChatGPT response. |
Effectively a duplicate of #33912, will watch this one. Will use function overloading in the meantime. |
π Search Terms
"not assignable",
"parametized argument",
"conditional return"
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.1.6#code/JYOwLgpgTgZghgYwgAgJIBMLmDYcBGANigN7LDoBcyAzmFKAOYDcyIcAthAPzV0MgWyAL4BYAFASYAVxAIwwAPYhkHAJ4y5AHgAqGMMggAPSCHQ00mbLgLFkAHzbTChAHwAKUDEU1qe9GAAlH76hiZY5pZYCjZEKNy09EzI1CDOhMgkEsg55DDIniDeFgC8JU4ugZnZubVQEGDSUCppLsw1tTkA9F0AolBQfmoADigA5K2EY+QWIIoGcDQ0wIzscchgihsj4-4GxqaRGNE4eOsJ-Mmp6WMAdO4ATADMDw+BHSKGhDSkH3UNTRUXh8two7XEnVyPX6g2QOh2yDGl0E02As3myEWy1WthQm22o0RezChwsx2sZzsFySghSFSm92er3eENyYnE7IkxAMYA4w2Q5XUmgQ7kmgXBPRKrmQ3I2fOuLi5DTlwweAtUGlkIpI7C41DGYwANOQqIixsJxRJJdLZbzVXwaYwJEA
π» Code
π Actual behavior
tsc
doesn't seem to match theif
statement with the conditional return.On the other hand it understand what I want to say when calling the method.
π Expected behavior
What I expect is for typescript to understand in the if that if the argument is
null
then I can only returnnull
, and alse only return astring
, like defined in the function signature.Additional information about the issue
I have the impression that the signature is correct as typescript infer correctly when calling the function, so the problem is inside the function with the
if
?The text was updated successfully, but these errors were encountered: