Skip to content

Commit 2ea6dfc

Browse files
crisbetoAndrewKushnir
authored andcommitted
fix(compiler-cli): update diagnostic to flag no-op arrow functions in listeners
Based on the discussion in #66294: now that we support arrow functions in event listeners, developers may write out something like `(click)="() => expr"` which will be a no-op. These changes update the existing diagnostic for uninvoked expressions in listeners to account for it.
1 parent 108252b commit 2ea6dfc

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/index.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
Conditional,
1515
ParsedEventType,
1616
PropertyRead,
17+
ArrowFunction,
1718
SafeCall,
1819
SafePropertyRead,
1920
TmplAstBoundEvent,
@@ -84,6 +85,12 @@ function assertExpressionInvoked(
8485
return []; // If the method is called, skip it.
8586
}
8687

88+
if (expression instanceof ArrowFunction) {
89+
const errorString =
90+
'Arrow function will not be invoked in this event listener. Did you intend to call a method?';
91+
return [ctx.makeTemplateDiagnostic(node.sourceSpan, errorString)];
92+
}
93+
8794
if (!(expression instanceof PropertyRead) && !(expression instanceof SafePropertyRead)) {
8895
return []; // If the expression is not a property read, skip it.
8996
}

packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,17 @@ runInEachFileSystem(() => {
193193

194194
expect(diags.length).toBe(0);
195195
});
196+
197+
it('should produce a diagnostic when an event listener is declared as an arrow function', () => {
198+
const diags = setupTestComponent(`<button (click)="() => 123"></button>`, ``);
199+
expect(diags.length).toBe(1);
200+
expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning);
201+
expect(diags[0].code).toBe(ngErrorCode(ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING));
202+
expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="() => 123"`);
203+
expect(diags[0].messageText).toBe(
204+
'Arrow function will not be invoked in this event listener. Did you intend to call a method?',
205+
);
206+
});
196207
});
197208
});
198209

0 commit comments

Comments
 (0)