microsoft / microsoft/TypeScript
Call signature returning a wide union type not seen as compatible with implementation
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
Bug Report
🔎 Search Terms
overload "not compatible" 2394 union return type
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about overloads and unions
⏯ Playground Link
Playground link with relevant code
💻 Code
function foo(x: true): 0 | 1; // error!
// ----> ~~~
// This overload signature is not compatible with its implementation signature.(2394)
function foo(x: false): 2;
function foo(x: boolean) {
return x ? 0 : 2;
}
🙁 Actual behavior
The compiler complains that the first call signature which returns 0 | 1 is not compatible with the implementation signature which returns 0 | 2.
🙂 Expected behavior
The compiler "should" allow the 0 | 1 call signature return type because of the significant overlap with 0 | 2.
So, this is probably not actually a bug, but I'm having a hard time locating any canonical documentation or issues that mention this particular behavior. It makes sense for the compiler to warn that a call signature is claiming to return something the implementation can never return, but in this particular instance (adapted from this SO question) it seems unfortunate/misplaced: while the implementation cannot return a value of type 1, it can return a value of type 0 | 1. Obviously there are workarounds, the easiest of which would be an explicit implementation return type annotation of the full union 0 | 1 | 2:
function foo(x: true): 0 | 1; // no error now
function foo(x: false): 2;
function foo(x: boolean): 0 | 1 | 2 {
return x ? 0 : 2;
}
So... is this working as intended? If so, could someone explain the intent? Thanks!
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the overload example in the linked TypeScript Playground and compare the reported compatibility error with the explicit implementation return-type workaround. Trace the compiler's overload compatibility behavior, then determine whether the result should be fixed or explained in canonical documentation and add coverage or documentation accordingly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100