-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
If statement return type with union inferred incorrectly #58617
Comments
This is expected subtype reduction behavior. Typescript can only infer your desired type in specific scenarios with fresh objects; see #19513. |
@nmain can you elaborate? TS correctly infers the type in each branch, and correctly infers the return type when a ternary is used. Edit: If anything I could imagine the reduction would reduce the return type to |
Because they're fresh object literals in that case. Search "subtype reduction" and you'll find various previous issues about this; for instance, #52893. |
@RyanCavanaugh why not infer
I would also add to @RyanCavanaugh's comment:
There will be confusion somewhere. But "you have a function call here, passing in the object, so we can't tell whether there are extra properties on it afterwards" is less confusing than the current behavior imo (this was a common issue in Flow, but people working with it learned it). So tracking object literals / "closeness" would be preferable. |
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
union, spread, return, inferrence
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.5.0-dev.20240522&ssl=16&ssc=1&pln=1&pc=1#code/PTAEBUAsEsGdQGYFcB2BjALtA9ig5PAE4CmGShKoGAngA7GiyTZIA2AJqAEbEBQIoAN60AXKBRIAtj0IBfUAB8hoidOKEANKEljYGQtBQBzWfzBckGUNCtxlY1TNNpcexKlABeUAAoXKdjEubGxWYgBDFABKLwA+IV5QUH83AA8vIVBRUABGUFkAbkTrBF9-dhjBYqSUqxdpQ2JOb0FQADoO1K0dUAAiSGJWVmxe-KKkpJIyCmTsBpQm8fzQQdgGKonQARJaVnC0BgB3G0hQAAMp8kpeoxD2XrPEbEJZwhJMUEuZmnpqz9IrqBUktTEkBFA7IdngBreAIRrFbYAmblUAAfkyHTaXW0Yn6g2Go3kYmBvEKvAp4Jg8ChhFhiAR7GIaD2JFmKDc5SCITCkSKtSBGWEIhy5IF1AyqIxrSxOJ6+KGI2WJIKQA
π» Code
π Actual behavior
The inferred function return type doesn't include both branches of the if statement.
π Expected behavior
The inferred function return type should include both branches of the if statement, as if ternary was used.
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: