简体   繁体   English

TypeScript中对象文字符号内的函数。 为什么`this`上下文是`any`类型的?

[英]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 */

Playground 操场

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? 我可以先声明一个类,然后实例化该对象,但是为什么不声明中间classinterface就无法工作,在这种简单情况下,它看起来像样板吗?

According to the official TypeScript Documentation on functions: 根据有关功能的官方TypeScript文档

[...] is still any . [...]仍然是any That's because this 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参数的签名在上下文中键入,则该方法具有该参数的类型。

  • Otherwise, if --noImplicitThis is enabled and the containing object literal has a contextual type that includes a ThisType, this has type T. 否则,如果启用了--noImplicitThis,并且包含的​​对象文字的上下文类型包含ThisType,则其类型为T。
  • Otherwise, if --noImplicitThis is enabled and the containing object literal has a contextual type that doesn't include a ThisType, this has the contextual type. 否则,如果启用了--noImplicitThis,并且包含的​​对象文字具有不包含ThisType的上下文类型,则该上下文类型为。
  • Otherwise, if --noImplicitThis is enabled this has the type of the containing object literal. 否则,如果启用--noImplicitThis,则具有包含对象文字的类型。
  • Otherwise, this has type any. 否则,此类型为any。

reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM