'this'隐式具有类型'any',因为它没有类型注释(TypeScript)

问题描述 投票:0回答:1

我有一个文件 .ts 并因以下代码收到此错误:

const hulk={
    nombre:'Hulk',
    smash(){

        setTimeout(function(){   
            console.log(`${ this.nombre} smash!`); //HERE is the error but IDK why
        },1000);

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

我正在学习使用箭头函数以及使用箭头函数和使用函数的区别,但是当我在函数中输入“this”这个词时出现错误,因为当我在箭头函数中使用“this”时一切正常.

我试过添加

"noImplicitAny": false,

tsconfig.json

但这没有用。

typescript function compiler-errors this arrow-functions
1个回答
0
投票

this
里面的
setTimeout
指的是函数上下文,而不是绿巨人对象。箭头函数不会创建自己的上下文(它们自己的 this),因为它们继承了它。

箭头函数表达式

© www.soinside.com 2019 - 2024. All rights reserved.