打字稿错误:此容器遮盖了外部值“ this”

时间:2019-05-19 02:44:58

标签: typescript class oop

我在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;
    };
}

2 个答案:

答案 0 :(得分:2)

在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; 
  };
};

答案 1 :(得分:2)

使用setTimeout上的箭头功能进行操作

setTimeout(() => {
  yourFunction()
}, 3000);