Ошибка машинописного текста: этот контейнер скрывает внешнее значение 'this' - PullRequest
3 голосов
/ 19 мая 2019

У меня была ошибка в объявлении метода класса Typescript, но я не понимаю, как сообщение об ошибке связано с ошибкой.

Похоже, в сообщении говорится, что «this» относится к типу any, но мы находимся в определении класса, и поэтому я подумал, что «this» действительно ясно.

Может кто-нибудь объяснить, как сообщение об ошибке относится к ошибке?

Оригинальный метод:

calcSize = function() {
    return this.width * this.length; // Error on this line
};

// Error text: 'this' implicitly has type 'any' because it does not 
//have a type annotation.ts(2683)
//app.ts(39, 16): An outer value of 'this' is shadowed by this container.

фикс:

calcSize() {
    return this.width * this.length;
};

Полный контекст (исправлено):

class BaseObject {
    constructor(
        public width: number = 0,
        public length: number = 0
        ) {}

};

class Rectangle extends BaseObject {

    constructor(public width: number = 0, public length: number = 0) {
        super(width, length);
    }

    calcSize() {
        return this.width * this.length;
    };
}

1 Ответ

3 голосов
/ 19 мая 2019

В TypeScript (и ES6) существует два вида функций: классическая функция объявление и функция стрелки . Там, где у классического объявления функции есть своя привязка для ключевого слова this - функция стрелки будет использовать значение для this контекста, содержащего функцию стрелки.

class Rectangle extends BaseObject {
// ..
  calcSize = function() {
    // the keyword function will cause that this will be re-bind
    // since the function is explicitly assigned to calcSize
    // it can not be recognized as a member therefore this will be any 
    return this.width * this.length; // Error on this line
  };
  calcSizeAsMember () {
    // is also a classic function which will re-bind
    // the this keyword, but it can be recognized as a member
    // therefore this will be the type of the containing class
    return this.width * this.length; 
  };
  calcSizeAsArrowFunction = () => {
    // is an arrow function which will NOT re-bind
    // the this keyword, this will always remain the value of the 
    // surrounding class
    return this.width * this.length; 
  };
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...