打字稿错误:此容器遮盖了外部值"this" [英] Typescript error: An outer value of 'this' is shadowed by this container
问题描述
我在Typescript类方法声明中有一个错误,但是我不明白该错误消息与该bug的关系.
I had an error in a Typescript class method declaration, but I don't understand how the error message relates back to the bug.
该消息似乎是说'this'是 any
类型,但是我们在类定义中,所以我认为'this'确实很清楚.
The message seems to be saying that 'this' is of type any
, but we are in a class definition, and so I thought 'this' was really clear.
有人可以解释一下错误消息与错误的关系吗?
Can someone please explain how the error message relates back to the 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;
};
}
推荐答案
在TypeScript(和ES6)中存在两种函数:经典的函数声明和箭头函数>.在经典函数声明具有 this
关键字的默认浮动绑定逻辑的情况下-箭头函数将不断使用包含箭头函数的上下文的 this
的值.在示例中,这将是周围类的实例.
In TypeScript (and ES6) exists two kinds of functions: The classic function declaration and the arrow function. Where the classic function declaration has the default floating binding logic for the this
keyword - the arrow function will constantly use the value for this
of the context containing the arrow function. In the example this will be the instance of the surrounding class.
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-bind 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 () {
// 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-bind by changing the context
// using bind or call
// -> Value of this defaults to the class instance
return this.width * this.length;
};
calcSizeAsArrowFunction = () => {
// is an arrow function which has a constantly bind this keyword,
// it is not possible to change the binding afterwords (not re-binding)
// type of this is constantly the type of the containing class
// changing the context, use bind or call will have no effect
// -> this will always remain to the instance of the class
return this.width * this.length;
};
};
这篇关于打字稿错误:此容器遮盖了外部值"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!