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


124

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.

타이프 스크립트 놀이터


TypeScript 2.1 또는 야간 버전에서 사용해 보셨습니까?
Daniel Rosenwasser

@DanielRosenwasser 2.1.4
tony19

이제 WebStorm과 TS 플레이 그라운드가 불평하는 이유를 알 수 있습니다. .NET에 유형 주석을 제공하는 동안 화살표 함수를 사용하고있었습니다 this.
tony19

2
여기에 버그를 신고했습니다 : github.com/Microsoft/TypeScript/issues/13768- 자유롭게 추적하고 좋아요를 눌러 주세요 .
Daniel Rosenwasser

답변:


139

오류는 실제로 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및 화살표 함수로 실제 문법 오류를 강조하기 위해 생성되었습니다 .


생성자에서 'this'를 사용하는 경우 'this'에는 어떤 유형 주석이 필요합니까?
BluE

@BluE 멤버 속성 / 함수를 참조한다고 가정하면 this초기화되는 클래스의 유형이됩니다. (가) 예를 들어, constructor클래스 인 MyClass에 대한 유형 약어가 this될 것이다 MyClass.
tony19 19
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.