it-source

'this'에는 형식 주석이 없으므로 암시적으로 형식 'any'가 있습니다.

criticalcode 2023. 3. 22. 21:38
반응형

'this'에는 형식 주석이 없으므로 암시적으로 형식 'any'가 있습니다.

유효하게 하면noImplicitThistsconfig.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콜백 파라미터에 대해 같은 에러가 발생합니다.

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그리고 화살을 쏘죠.

구성을 포함한 메서드 데코레이터 선언의 경우"noImplicitAny": true,이 변수의 유형을 지정할 수 있습니다. @syslog19의 답변에 따라 명시적으로 달라집니다.

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

tsconfig.json에서 "noImplicitAny"를 false로 변경해도 도움이 되지 않습니다.해 보다"noImplicitThis": falsetsconfig.json에서

타이프 스크립트에서는,this는 함수 파라미터의 키워드입니다.

답을 보세요.

추가할 수 있습니다.

 "noImplicitAny": false,

로.

tsconfig.json

여기서 말하는 바와 같이

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

반응형