当我在
noImplicitThis
中启用tsconfig.json
时,我得到以下代码的错误:
'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:
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');
});
但是这个错误的正确解决方法是什么?
更新: 事实证明,向回调中添加类型化的
this
确实解决了错误。我看到错误是因为我使用了带有 this
: 类型注释的箭头函数
错误确实通过插入带有类型注释的
this
作为第一个回调参数来修复。我这样做的尝试被同时将回调更改为箭头函数而搞砸了:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
应该是这样的:
foo.on('error', function(this: Foo, err: any) {
或者这个:
foo.on('error', function(this: typeof foo, err: any) {
创建了 GitHub issue 以改进编译器的错误消息并使用
this
和箭头函数突出显示实际语法错误。
用于方法装饰器声明 带配置
"noImplicitAny": true,
您可以根据@tony19 的回答明确指定此变量的类型
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
在 tsconfig.json 中将“noImplicitAny”更改为 false 没有帮助。尝试在 tsconfig.json
中执行
"noImplicitThis": false
在角度开发服务器启动期间我收到以下错误
"Error: node_modules/grapesjs/index.d.ts:29:5 - error TS7010: 'each', which lacks return-type annotation, implicitly has an 'any' return type."
现在当我到达这个错误文件路径时,VS CODE IDE 在每个方法悬停时显示以下错误消息
'each' implicitly has an 'any' return type, but a better type may be inferred from usage.ts(7050)
所以我在
tsconfig.json
文件中做了以下更改
// add or made change below option in the tsconfig.json file
"noImplicitAny": false,
禁用该功能不是个好主意,但角度不允许运行它显示错误的项目。所以我添加了代码并执行得很好。