Skip to content
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

Wrong return type for union of overloaded functions #55203

Closed
maledies opened this issue Jul 30, 2023 · 2 comments Β· Fixed by #55447
Closed

Wrong return type for union of overloaded functions #55203

maledies opened this issue Jul 30, 2023 · 2 comments Β· Fixed by #55447
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@maledies
Copy link

Bug Report

πŸ”Ž Search Terms

union, overload, function, return type

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (4.4, 4.8, 5.0, 5.1, 5.2beta)

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface Callable<Name extends string> {
	(): `${Name} without id`
	(id: number): `${Name} with id`
}

declare const f: Callable<"A"> | Callable<"B">
const result = f(123) //results in "A with id"|"B without id"

πŸ™ Actual behavior

result is inferred as "A with id"|"B without id".

"B with id" is completely missing and "B without id" should not appear since we used a parameter.

πŸ™‚ Expected behavior

result is "A with id"|"B with id".

@MartinJohns
Copy link
Contributor

I believe it's the same as: #55101 (comment)

The contextual type for the return type of the function expression in this case comes from the first overload, since it's the first one that appears to match on arity.

The first overload that matches the arity is the first one, without any arguments (providing too many arguments is fine).

You can fix your code by changing the order of overloads from most specific to least specific:

interface Callable<Name extends string> {
	(id: number): `${Name} with id`
	(): `${Name} without id`
}

@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Aug 1, 2023
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Aug 1, 2023
@RyanCavanaugh
Copy link
Member

There's no contextual type or widening here. Definitely better to write it with the overloads in the other order, though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants