typescript 错误:'this'的外部值被这个容器遮蔽

vu8f3i0k  于 2022-12-14  发布在  TypeScript
关注(0)|答案(3)|浏览(678)

我在Typescript类方法声明中遇到了一个错误,但我不明白错误消息与bug之间的关系。
消息似乎是说'this'的类型是any,但我们是在类定义中,所以我认为'this'非常清楚。
有人能解释一下错误消息是如何与bug相关的吗?
原始方法:

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

fkvaft9z1#

在TypeScript(和ES6)中存在两种函数:经典函数声明和箭头函数。其中经典函数声明具有this关键字的默认浮点绑定逻辑-箭头函数将始终使用包含箭头函数的上下文中this的值。在本示例中,这将是周围类的示例。

class Rectangle extends BaseObject {
  // ..
  calcSize = function() {
    // The keyword "function" will cause "this" to be floating.
    // Since the function is explicitly assigned to calcSize
    // (older) TypeScript may not infer the type of "this".
    // The value of "this" can be re-bound by changing the context
    // using bind or call.
    // -> Value of "this" defaults to the class instance
    return this.width * this.length; // (potential) type Error on this line
  };

  calcSizeAsMember () {
    // This is also a classic function which will use floating binding
    // therefore "this" will be the type of the containing class.
    // The value of "this" can be re-bound by changing the context
    // using bind or call.
    // -> Value of "this" defaults to the class instance
    return this.width * this.length; 
  };

  calcSizeAsArrowFunction = () => {
    // This is an arrow function which has a constantly-bound "this" keyword, 
    // it is not possible to re-bind afterward.
    // The type of "this" is always the type of the containing class.
    // Changing the context using bind or call will have no effect
    // -> Value of "this" is always the class instance
    return this.width * this.length;
  };

};
fumotvh3

fumotvh32#

在做了一些研究之后,我发现了一些有趣的事情。“this”可以是正则函数(不是箭头函数)的参数,类型可以是“any”或“unknown”
声明函数时,请注意“this”的类型“any”。

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

    }
}
7kqas0il

7kqas0il3#

使用setTimeout上的箭头函数执行此操作

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

相关问题