[英]Functions within object literal notation in TypeScript. Why `this` context is of type `any`?
Perhaps the question was already asked, but I could not find any. 也许已经有人问过这个问题,但我找不到。 And it seems so naive.
而且看起来太幼稚了。 TypeScript comes well with object literal notation, but when defining the methods within, than it can't properly handle
this
context inside that functions, it seems this
receives any
type, so there is no auto-completion. 打字稿与对象的文字符号来不错,但定义内,比它不能正确处理方法时,
this
是里面的功能方面,似乎this
收到any
类型的,所以不存在自动完成。
var foo = {
log(str) {
console.log(str);
},
print(str) {
this. /* No autocompletion */
}
};
foo. /* Normal autocompletion */
Naturally, I would expect that the autocompletion properly works in method, the same way it does when consuming foo
variable. 自然,我希望自动补全可以在方法中正常工作,就像使用
foo
变量时一样。 I could declare a class first, then instantiate the object, but why it doesn't work without declaring intermediate class
or interface
, in this simple case it seems like a boilerplate? 我可以先声明一个类,然后实例化该对象,但是为什么不声明中间
class
或interface
就无法工作,在这种简单情况下,它看起来像样板吗?
According to the official TypeScript Documentation on functions: 根据有关功能的官方TypeScript文档 :
[...] is still
any
.[...]仍然是
any
。 That's becausethis
comes from the function expression inside the object literal.这是因为
this
来自对象文字内部的函数表达式。
The TypeScript Wiki on GitHub also has good explanations about the this
keyword and its context. GitHub上的TypeScript Wiki也对
this
关键字及其上下文有很好的解释。
For future reference: Since TS@2.3, this behaviour is a little bit more complicated: 供将来参考:自TS@2.3起,此行为稍微复杂一些:
If the method has an explicitly declared this parameter, this has the type of that parameter. 如果该方法具有显式声明的此参数,则此参数具有该参数的类型。
Otherwise, if the method is contextually typed by a signature with a this parameter, this has the type of that parameter. 否则,如果该方法由带有this参数的签名在上下文中键入,则该方法具有该参数的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.