development

'this'에는 유형 어노테이션이 없기 때문에 암시 적으로 'any'유형이 있습니다.

big-blog 2020. 9. 12. 11:14
반응형

'this'에는 유형 어노테이션이 없기 때문에 암시 적으로 'any'유형이 있습니다.


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

this콜백 매개 변수에 typed 추가 하면 동일한 오류가 발생합니다.

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 문제 는 컴파일러의 오류 메시지를 개선하고 this및 화살표 함수로 실제 문법 오류를 강조하기 위해 생성되었습니다 .

참고 URL : https://stackoverflow.com/questions/41944650/this-implicitly-has-type-any-because-it-does-not-have-a-type-annotation

반응형