You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中普通函数this隐式any报错问题求助

问题原因分析

普通函数与箭头函数的this绑定规则存在本质差异,导致TypeScript的类型推断行为不同:

  • 普通函数:this的指向在函数调用时才确定,setTimeout里的普通函数执行时,this默认绑定全局对象(浏览器环境为window,Node.js环境为globalThis),TypeScript无法自动推断该this的具体类型,因此抛出"'this' implicitly has type 'any'"的错误。
  • 箭头函数:没有独立的this,会继承外层作用域的this(也就是smash方法中的this,指向hulk对象),TypeScript能明确推断出this的类型,所以不会报错。

你设置"noImplicitAny": false无效,是因为TypeScript的strict模式(默认可能开启)包含了noImplicitThis规则——该规则专门检查this的隐式any类型,即便关闭noImplicitAny,noImplicitThis依然会生效。

解决方案

1. 显式指定普通函数的this类型

在普通函数的参数列表开头声明this的类型,明确告诉TypeScript该函数内this的指向:

const hulk = {
    nombre: 'Hulk',
    smash() {
        // 声明this的类型为hulk对象的类型
        setTimeout(function(this: typeof hulk) {   
            console.log(`${ this.nombre} smash!`);
        }, 1000);

        setTimeout(() => {
            console.log(`${ this.nombre} smash!`);
        }, 1000);
    }
}
hulk.smash();

2. 提前保存this到变量

在smash方法内先将this赋值给一个变量,普通函数中用该变量替代this:

const hulk = {
    nombre: 'Hulk',
    smash() {
        const that = this;
        setTimeout(function() {   
            console.log(`${ that.nombre} smash!`);
        }, 1000);

        setTimeout(() => {
            console.log(`${ this.nombre} smash!`);
        }, 1000);
    }
}
hulk.smash();

3. 继续使用箭头函数

这是当前场景下最简洁的方案,箭头函数天然继承外层this,完全符合你的需求,无需额外修改。

(不推荐)关闭noImplicitThis规则

若一定要通过关闭规则解决问题,需在tsconfig.json中同时设置:

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noImplicitThis": false
    }
}

但该做法会弱化TypeScript的类型检查能力,不建议长期使用。

内容的提问来源于stack exchange,提问作者user21659477

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:07:19