'Dies' hat implizit den Typ 'any', weil es keine Typannotation hat

Wenn ich Sie aktivieren noImplicitThis im tsconfig.jsonbekomme ich diese Fehler für den folgenden code:

'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`
});

Hinzufügen eines typisierten this den callback-Parametern ergibt sich der gleiche Fehler:

foo.on('error', (this: Foo, err: any) => { //error: `this` implicitly has type `any`

Ist ein workaround zu ersetzen this mit dem Objekt:

foo.on('error', (err: any) => {
  console.log(err);
  foo.emit('end');
});

Aber was ist die richtige fix für diesen Fehler?


UPDATE: Es stellt sich heraus, das hinzufügen einer typisierten this an die callback-in der Tat behebt die Fehler. Ich sah die Fehler, da war ich mit einem Pfeil-Funktion mit einem Typ-annotation für this:

'Dies' hat implizit den Typ 'any', weil es keine Typannotation hat

InformationsquelleAutor der Frage tony19 | 2017-01-30

Schreibe einen Kommentar