Angular引入jQuery时出现ts(2683)this隐式为any类型报错求助
报错根因
出现'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)且配置"noImplicitAny": false不生效,通常有两个原因:
- 修改tsconfig后没有重启TS服务、没有重启Angular本地开发进程,或者修改的tsconfig文件不在当前项目的编译生效范围内
- 代码里使用普通
function作为jQuery方法的回调时,TS无法自动推断回调内this的上下文类型,即使关闭全局隐式any校验,部分IDE的本地类型检查仍会抛出该提示,完全不需要靠关闭校验规则绕开。
另外你的代码里还有一个会直接导致组件无法运行的低级错误:装饰器写的是小写开头的@component,Angular的组件装饰器必须是大写开头的@Component。
修复方案
- 不要依赖关闭
noImplicitAny规避类型问题,直接给回调内的this显式标注类型,从根源消除报错 - 修正装饰器大小写错误
- 复用已经缓存的jQuery对象,减少重复DOM查询,同时避免二次引用
this带来的类型推断问题 - 如果配置修改后不生效,在VS Code中通过命令面板执行
Restart TS Server重启TS服务,同时终止并重新运行ng serve启动开发服务,确保配置加载。
修复后可直接运行的代码
import { Component, OnInit } from '@angular/core'; declare var $: any; @Component({ selector: 'app-color-change', templateUrl: './color-change.component.html', styleUrls: ['./color-change.component.scss'] }) export class ColorChangeComponent implements OnInit { ngOnInit(): void { $(window).on('scroll', () => { const $window = $(window); const $body = $('body'); const $panel = $('.panel'); // 提前1/3视口高度触发切换,保证滚动到对应面板时主题色已完成切换 const scroll = $window.scrollTop() + ($window.height() / 3); $panel.each(function (this: HTMLElement) { const $this = $(this); // 校验当前滚动位置是否落在当前面板区间内 if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) { // 移除body上所有color-前缀的主题类 $body.removeClass(function (_index: number, css: string) { return (css.match(/(^|\s)color-\S+/g) || []).join(' '); }); // 绑定当前面板对应的主题类 $body.addClass(`color-${$this.data('color')}`); } }); }).scroll(); } }
关键修改点说明
- 修正了
@component为Angular要求的大写@Component装饰器 - 给
$panel.each的回调函数显式标注this: HTMLElement,直接解决TS2683类型报错 - 滚动事件回调改用箭头函数,避免不必要的this指向偏移,符合Angular+TS编码规范
- 复用回调内已缓存的
$this对象读取data-color属性,避免重复包装DOM对象,也消除了二次引用this的类型问题 - 给
removeClass的回调参数添加了类型标注,避免其他隐式any报错
内容的提问来源于stack exchange,提问作者Tito Araujo
相关产品推荐
相关产品推荐

