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

cha*_*ham 5 oop class typescript

我在Typescript类方法声明中有一个错误,但是我不明白该错误消息与该bug的关系。

消息似乎是在说'this'是type 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.
Run Code Online (Sandbox Code Playgroud)

固定:

calcSize() {
    return this.width * this.length;
};
Run Code Online (Sandbox Code Playgroud)

完整上下文(固定):

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;
    };
}
Run Code Online (Sandbox Code Playgroud)

Wol*_*eon 10

经过一些研究后,我发现了一些有趣的事情。“this”可以是常规函数(不是箭头函数)的参数,类型可以是“any”或“unknown”

注意声明函数时“this”的类型“any”。

export async function main(this: any) {
    try {
        console.log(this);
    } catch (e: any) {

    }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*her 7

在TypeScript(和ES6)中存在两种函数:经典函数声明和arrow函数。如果经典函数声明具有自己的this关键字绑定,则arrow函数将使用this包含arrow函数的上下文的value作为。

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; 
  };
};
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要指出标准方法声明未绑定到类实例 - 例如,如果您获取对它的引用并将其称为 `this` 将是全局上下文。`let ref = rect.calcSizeAsMember; 参考()`。在使用异步代码时,这可能是一个常见的问题 (2认同)