当我启用noImplicitThis
in tsconfig.json
,我收到以下代码的错误:
“this”隐式具有类型“any”,因为它没有类型
注解。
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`
});
添加一个打字的this
回调参数会导致相同的错误:
foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
解决方法是更换this
与对象:
foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
但是这个错误的正确修复方法是什么?
UPDATE:事实证明添加了一个键入的this
回调确实解决了错误。我看到错误是因为我使用带有类型注释的箭头函数this
:
该错误确实通过插入来修复this
使用类型注释作为第一个回调参数。我的尝试通过同时将回调更改为箭头函数而失败:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
本来应该是这样的:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
一个GitHubissue https://github.com/Microsoft/TypeScript/issues/13768创建是为了改进编译器的错误消息并突出显示实际的语法错误this
和箭头函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)