microsoft / microsoft/TypeScript
Improve error message for incompatible signatures in union type from typed/untyped function call
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
untyped function call error message union type incompatible signature
Example
This code errors as follows:
function foo<T>(x: T | (() => string)) {
if (typeof x === "function") {
let a = x();
// ^ Cannot invoke an expression whose type lacks a call signature.
//Type '(() => string) | (T & Function)' has no compatible call signatures. [2349]
}
}
which feels strange given that both of the following are fine:
function fooL<T>(x: T) {
if (typeof x === "function") {
let a = x();
}
}
function fooR(x: () => string) {
if (typeof x === "function") {
let a = x();
}
}
If an evaluation contexts accepts values of type A and values of type B, then it should accepts values of type A | B. I think what is going on is that the call signature from T & Function is untyped, which is incompatible with the typed signature of () => string.
I don't think this is very obvious to a user, and they end up seeing an application that works for both branches of a union, but not their composition.
Suggestion
I think making the example work is out of scope. My suggestion is to improve the error message, something like:
function foo<T>(x: T | (() => string)) {
if (typeof x === "function") {
let a = x();
// ^ Cannot invoke an expression whose type lacks a call signature.
// Type '(() => string) | (T & Function)' has no compatible call signatures. [2349]
// Cannot combine untyped function call with typed function call
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)
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 running the TypeScript example in the issue and search the compiler diagnostics for error 2349. Trace how the union's call signatures produce the current message. Done means the incompatible typed and untyped function calls receive a clearer explanatory diagnostic, with the existing examples still covered.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100