【问题标题】:Vue Typescript callback: this implicitly has type anyVue Typescript 回调:this 隐含类型为 any
【发布时间】:2021-12-11 07:26:48
【问题描述】:

在我的 vue 组件中使用带有 lodash debounce 的匿名函数作为 watch 选项时,我收到 typescript 编译器错误“这隐含地具有任何类型。

这是我的组件

export default defineComponent({
  data(){
    return {
       filters:{
          filter1: "foo"
       } as Record<string, string>
    }
  },
  methods:{
    load(){
       //load function
    }
  },
  watch:{
    "filters":{
       deep: true,
       handler:_debounce(function(newValue){
           this.load() // <= hear I got "this implicitly has type any"
       }, 500)
    }
  }
})

我在这篇文章中发现我的匿名去抖回调函数使用箭头函数,但错误仍然存​​在 (TS2683 (TS) 'this' implicitly has type 'any' because it does not have a type annotation)

另一种解决方案是将“this:any”作为参数传递给函数,但我发现这很丑。

_debounce(function(this:any, newValue){
           this.load() // <= hear I got "this implicitly has type any"
       }, 500)

有没有更好的解决方案来处理这个问题? (没有将 noImplicitAny 设置为 false)

【问题讨论】:

    标签: typescript vue.js compiler-construction debounce


    【解决方案1】:

    尝试使用'箭头'函数定义,以保持this的范围。

    handler:_debounce(() => {
           this.load() 
       }, 500)
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    编辑: 对于这种情况,打字稿中的一些设计限制使得难以检测/分配类型到隐式this(请参阅 https://github.com/microsoft/TypeScript/issues/38845#issuecomment-651455328) 它应该使用带有类型参数的函数表达式,在自定义接口中定义,例如:

    interface ComponentInterface {
      load(): void
    }
    

    然后:

    _debounce(function(this:ComponentInterface, newValue){
           this.load()
       }, 500)
    

    你可以在https://v3.vuejs.org/guide/typescript-support.html#using-with-options-api找到几个使用这种方式定义类型/注释的案例

    【讨论】:

    • 当我使用箭头函数时,我得到一个“对象可能未定义”,如果我执行“this?.load()”,我得到“属性'load'不存在于类型'never '。它不能解决问题:(
    • 我已经为这个案例添加了一些 cmets/references 和示例,请尝试一下,让我知道它是否适合你
    • 谢谢!这就是我要找的。我想确定除此之外没有其他解决方案
    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 2019-08-04
    • 2017-06-16
    • 2020-09-25
    • 2019-06-08
    • 2021-09-27
    • 1970-01-01
    • 2020-03-06
    相关资源
    最近更新 更多