typescript “this”隐式具有类型“any”,因为它没有类型注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41944650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'this' implicitly has type 'any' because it does not have a type annotation
提问by tony19
When I enable noImplicitThis
in tsconfig.json
, I get this error for the following code:
当我启用noImplicitThis
in 时tsconfig.json
,我收到以下代码的错误:
'this' implicitly has type 'any' because it does not have a type annotation.
'this' implicitly has type 'any' because it does not have a type annotation.
class Foo implements EventEmitter {
on(name: string, fn: Function) { }
emit(name: string) { }
}
const foo = new Foo();
foo.on('error', function(err: any) {
console.log(err);
this.emit('end'); // error: `this` implicitly has type `any`
});
Adding a typed this
to the callback parameters results in the same error:
将 typed 添加this
到回调参数会导致相同的错误:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
A workaround is to replace this
with the object:
解决方法是this
用对象替换:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
But what is the proper fix for this error?
但是这个错误的正确修复是什么?
UPDATE:It turns out adding a typed this
to the callback indeed addresses the error. I was seeing the error because I was using an arrow function with a type annotation for this
:
更新:事实证明,向this
回调添加类型确实解决了错误。我看到错误是因为我使用了带有类型注释的箭头函数this
:
回答by tony19
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
该错误确实通过插入this
类型注释作为第一个回调参数来修复。通过同时将回调更改为箭头函数,我的尝试失败了:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
应该是这样的:
foo.on('error', function(this: Foo, err: any) {
or this:
或这个:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issuewas created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
创建了一个 GitHub问题来改进编译器的错误消息,this
并使用箭头函数突出显示实际的语法错误。