Skip to content

Improved error message for calling/constructing types #32034

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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 121 additions & 32 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21298,8 +21298,34 @@ namespace ts {
return Debug.fail();
}
}
function getDiagnosticSpanForCallNode(node: CallExpression, doNotIncludeArguments?: boolean) {
let start: number;
let length: number;
const sourceFile = getSourceFileOfNode(node);

function getArgumentArityError(node: Node, signatures: ReadonlyArray<Signature>, args: ReadonlyArray<Expression>) {
if (isPropertyAccessExpression(node.expression)) {
const nameSpan = getErrorSpanForNode(sourceFile, node.expression.name);
start = nameSpan.start;
length = doNotIncludeArguments ? nameSpan.length : node.end - start;
}
else {
const expressionSpan = getErrorSpanForNode(sourceFile, node.expression);
start = expressionSpan.start;
length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
}
return { start, length, sourceFile };
}
function getDiagnosticForCallNode(node: CallLikeExpression, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): DiagnosticWithLocation {
if (isCallExpression(node)) {
const { sourceFile, start, length } = getDiagnosticSpanForCallNode(node);
return createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2, arg3);
}
else {
return createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
}
}

function getArgumentArityError(node: CallLikeExpression, signatures: ReadonlyArray<Signature>, args: ReadonlyArray<Expression>) {
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let belowArgCount = Number.NEGATIVE_INFINITY;
Expand Down Expand Up @@ -21346,11 +21372,11 @@ namespace ts {
}
}
if (min < argCount && argCount < max) {
return createDiagnosticForNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
}

if (!hasSpreadArgument && argCount < min) {
const diagnostic = createDiagnosticForNode(node, error, paramRange, argCount);
const diagnostic = getDiagnosticForCallNode(node, error, paramRange, argCount);
return related ? addRelatedInfo(diagnostic, related) : diagnostic;
}

Expand Down Expand Up @@ -21425,8 +21451,7 @@ namespace ts {
reorderCandidates(signatures, candidates);
if (!candidates.length) {
if (reportErrors) {
const errorNode = getCallErrorNode(node);
diagnostics.add(createDiagnosticForNode(errorNode, Diagnostics.Call_target_does_not_contain_any_signatures));
diagnostics.add(getDiagnosticForCallNode(node, Diagnostics.Call_target_does_not_contain_any_signatures));
}
return resolveErrorCall(node);
}
Expand Down Expand Up @@ -21504,45 +21529,32 @@ namespace ts {
// If candidate is undefined, it means that no candidates had a suitable arity. In that case,
// skip the checkApplicableSignature check.
if (reportErrors) {
const errorNode = getCallErrorNode(node);

if (candidateForArgumentError) {
checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, CheckMode.Normal, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(errorNode, [candidateForArgumentArityError], args));
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
}
else if (candidateForTypeArgumentError) {
checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression | JsxOpeningLikeElement).typeArguments!, /*reportErrors*/ true, fallbackError);
}
else {
const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments));
if (signaturesWithCorrectTypeArgumentArity.length === 0) {
diagnostics.add(getTypeArgumentArityError(errorNode, signatures, typeArguments!));
diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!));
}
else if (!isDecorator) {
diagnostics.add(getArgumentArityError(errorNode, signaturesWithCorrectTypeArgumentArity, args));
diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
}
else if (fallbackError) {
diagnostics.add(createDiagnosticForNode(errorNode, fallbackError));
diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
}
}
}

return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);

function getCallErrorNode(node: CallLikeExpression): Node {
if (isCallExpression(node)) {
if (isPropertyAccessExpression(node.expression)) {
return node.expression.name;
}
else {
return node.expression;
}
}
return node;
}

function chooseOverload(candidates: Signature[], relation: Map<RelationComparisonResult>, signatureHelpTrailingComma = false) {
candidateForArgumentError = undefined;
candidateForArgumentArityError = undefined;
Expand Down Expand Up @@ -21825,7 +21837,7 @@ namespace ts {
relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon);
}
}
invocationError(node, apparentType, SignatureKind.Call, relatedInformation);
invocationError(node.expression, apparentType, SignatureKind.Call, relatedInformation);
}
return resolveErrorCall(node);
}
Expand Down Expand Up @@ -21942,7 +21954,7 @@ namespace ts {
return signature;
}

invocationError(node, expressionType, SignatureKind.Construct);
invocationError(node.expression, expressionType, SignatureKind.Construct);
return resolveErrorCall(node);
}

Expand Down Expand Up @@ -22015,11 +22027,88 @@ namespace ts {
return true;
}

function invocationError(node: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) {
const diagnostic = error(node, (kind === SignatureKind.Call ?
Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures :
Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature
), typeToString(apparentType));
function invocationErrorDetails(apparentType: Type, kind: SignatureKind): DiagnosticMessageChain {
let errorInfo: DiagnosticMessageChain | undefined;
const isCall = kind === SignatureKind.Call;
if (apparentType.flags & TypeFlags.Union) {
const types = (apparentType as UnionType).types;
let hasSignatures = false;
for (const constituent of types) {
const signatures = getSignaturesOfType(constituent, kind);
if (signatures.length !== 0) {
hasSignatures = true;
if (errorInfo) {
// Bail early if we already have an error, no chance of "No constituent of type is callable"
break;
}
}
else {
// Error on the first non callable constituent only
if (!errorInfo) {
errorInfo = chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.Type_0_has_no_call_signatures :
Diagnostics.Type_0_has_no_construct_signatures,
typeToString(constituent)
);
errorInfo = chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.Not_all_constituents_of_type_0_are_callable :
Diagnostics.Not_all_constituents_of_type_0_are_constructable,
typeToString(apparentType)
);
}
if (hasSignatures) {
// Bail early if we already found a siganture, no chance of "No constituent of type is callable"
break;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's with the annotation?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mistake, will delete

}
}
}
if (!hasSignatures) {
errorInfo = chainDiagnosticMessages(
/* detials */ undefined,
isCall ?
Diagnostics.No_constituent_of_type_0_is_callable :
Diagnostics.No_constituent_of_type_0_is_constructable,
typeToString(apparentType)
);
}
if (!errorInfo) {
errorInfo = chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other,
typeToString(apparentType)
);
}
}
else {
errorInfo = chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.Type_0_has_no_call_signatures :
Diagnostics.Type_0_has_no_construct_signatures,
typeToString(apparentType)
);
}
return chainDiagnosticMessages(
errorInfo,
isCall ?
Diagnostics.This_expression_is_not_callable :
Diagnostics.This_expression_is_not_constructable
);
}
function invocationError(errorTarget: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) {
const diagnostic = createDiagnosticForNodeFromMessageChain(errorTarget, invocationErrorDetails(apparentType, kind));
if (isCallExpression(errorTarget.parent)) {
const { start, length } = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true);
diagnostic.start = start;
diagnostic.length = length;
}
diagnostics.add(diagnostic);
invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}

Expand Down Expand Up @@ -22057,7 +22146,7 @@ namespace ts {
}

if (!callSignatures.length) {
invocationError(node, apparentType, SignatureKind.Call);
invocationError(node.tag, apparentType, SignatureKind.Call);
return resolveErrorCall(node);
}

Expand Down Expand Up @@ -22113,9 +22202,9 @@ namespace ts {

const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
if (!callSignatures.length) {
let errorInfo = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType));
let errorInfo = invocationErrorDetails(apparentType, SignatureKind.Call);
errorInfo = chainDiagnosticMessages(errorInfo, headMessage);
const diag = createDiagnosticForNodeFromMessageChain(node, errorInfo);
const diag = createDiagnosticForNodeFromMessageChain(node.expression, errorInfo);
diagnostics.add(diag);
invocationErrorRecovery(apparentType, SignatureKind.Call, diag);
return resolveErrorCall(node);
Expand Down
36 changes: 34 additions & 2 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1236,15 +1236,15 @@
"category": "Error",
"code": 2348
},
"Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures.": {
"This expression is not callable.": {
"category": "Error",
"code": 2349
},
"Only a void function can be called with the 'new' keyword.": {
"category": "Error",
"code": 2350
},
"Cannot use 'new' with an expression whose type lacks a call or construct signature.": {
"This expression is not constructable.": {
"category": "Error",
"code": 2351
},
Expand Down Expand Up @@ -2621,6 +2621,38 @@
"category": "Error",
"code": 2754
},
"No constituent of type '{0}' is callable.": {
"category": "Error",
"code": 2755
},
"Not all constituents of type '{0}' are callable.": {
"category": "Error",
"code": 2756
},
"Type '{0}' has no call signatures.": {
"category": "Error",
"code": 2757
},
"Each member of the union type '{0}' has signatures, but none of those signatures are compatible with each other.": {
"category": "Error",
"code": 2758
},
"No constituent of type '{0}' is constructable.": {
"category": "Error",
"code": 2759
},
"Not all constituents of type '{0}' are constructable.": {
"category": "Error",
"code": 2760
},
"Type '{0}' has no construct signatures.": {
"category": "Error",
"code": 2761
},
"Each member of the union type '{0}' has construct signatures, but none of those signatures are compatible with each other.": {
"category": "Error",
"code": 2762
},

"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
Expand Down
8 changes: 4 additions & 4 deletions src/services/codefixes/fixInvalidImportSyntax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@ namespace ts.codefix {

registerCodeFix({
errorCodes: [
Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code,
Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code,
Diagnostics.This_expression_is_not_callable.code,
Diagnostics.This_expression_is_not_constructable.code,
],
getCodeActions: getActionsForUsageOfInvalidImport
});

function getActionsForUsageOfInvalidImport(context: CodeFixContext): CodeFixAction[] | undefined {
const sourceFile = context.sourceFile;
const targetKind = Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? SyntaxKind.CallExpression : SyntaxKind.NewExpression;
const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), a => a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length)) as CallExpression | NewExpression;
const targetKind = Diagnostics.This_expression_is_not_callable.code === context.errorCode ? SyntaxKind.CallExpression : SyntaxKind.NewExpression;
const node = findAncestor(getTokenAtPosition(sourceFile, context.span.start), a => a.kind === targetKind) as CallExpression | NewExpression;
if (!node) {
return [];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts(7,1): error TS2554:
function bar(a, b, [c]): void {}

foo("", 0);
~~~
~~~~~~~~~~
!!! error TS2554: Expected 3 arguments, but got 2.
!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:1:20: An argument matching this binding pattern was not provided.

bar("", 0);
~~~
~~~~~~~~~~
!!! error TS2554: Expected 3 arguments, but got 2.
!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:3:20: An argument matching this binding pattern was not provided.

2 changes: 1 addition & 1 deletion tests/baselines/reference/baseCheck.errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'.
}

class D extends C { constructor(public z: number) { super(this.z) } } // too few params
~~~~~
~~~~~~~~~~~~~
!!! error TS2554: Expected 2 arguments, but got 1.
!!! related TS6210 tests/cases/compiler/baseCheck.ts:1:34: An argument for 'y' was not provided.
~~~~
Expand Down
Loading