如何在Closure Compiler中为函数指定this的类型?
this Type in Closure Compiler for jQuery Event Handlers I’ve run into this exact issue before when chasing 100% type coverage with Closure Compiler and jQuery. The problem with your initial approach is that the /** function(this:Element) */ comment might not be parsed correctly by the compiler—especially if you aren’t pairing it with proper jQuery type definitions or using the most explicit annotation syntax. Here’s how to fix it:
1. Use Inline this Type Annotation in the Function Definition
Closure Compiler supports directly specifying the this type in the function parameter list (before any actual parameters). This is often more reliable than standalone function type comments:
$Controls.on('change input', function(this: Element) { $(this).removeClass('is-invalid').next('.invalid-feedback').remove(); });
If your callback accepts the event object, you can add that parameter with its type too for full type safety:
$Controls.on('change input', function(this: Element, e: Event) { $(this).removeClass('is-invalid').next('.invalid-feedback').remove(); });
2. Explicitly Annotate $Controls with a JQuery Type
Sometimes the compiler gets confused about the type of your jQuery object itself. Adding a type annotation to $Controls helps the compiler infer the event handler’s context correctly:
/** @type {JQuery} */ const $Controls = $('.your-control-selector'); $Controls.on('change input', function(this: Element) { $(this).removeClass('is-invalid').next('.invalid-feedback').remove(); });
3. Use the @this JSDoc Tag (Alternative)
If you prefer JSDoc-style annotations over inline type hints, make sure the @this tag is directly associated with the callback function. Your initial comment was close, but tight binding between the comment and function ensures the compiler picks it up:
$Controls.on('change input', /** @this {Element} */ function(e) { $(this).removeClass('is-invalid').next('.invalid-feedback').remove(); });
Critical Pre-Requisite: Load jQuery’s Closure Type Definitions
None of these fixes will work if the compiler doesn’t have access to jQuery’s official Closure-compatible type definitions. Make sure you’re including the type definitions (either from the jQuery source with embedded JSDoc, or a standalone type file) when running the compiler. Without these, the compiler can’t understand the on method’s callback context at all.
The reason your initial attempt failed is likely that the standalone function(this:Element) comment wasn’t being linked properly to the callback, or the compiler lacked jQuery type info to validate the context. Using the inline this: Element syntax is the most direct way to enforce the type, and combining it with explicit type annotations for your jQuery variables will eliminate that warning for good.
内容的提问来源于stack exchange,提问作者Brian Leishman

