打字稿:具有较高阶函数的“ this”的推论

时间:2019-11-12 11:23:36

标签: typescript

当我在对象文字中定义函数时,Typescript将正确识别this的类型,例如:

const test = {
  foo: function() {
    return { type: 'foo' }
  },
  bar: function() {
    // Usage of "this" is fine for Typescript.
    return { type: 'bar', foo: this.foo() }
  }
}

当我使用高阶函数包装函数时,这会中断:

// Some HOC passing through the "this" parameter.
function cacheValue<THIS, RESULT>(
  factory: (this: THIS) => RESULT
): (this: THIS) => RESULT {
  let instance: RESULT | undefined
  return function() {
    if (instance === undefined) {
      instance = factory.call(this)
    }
    return instance
  }
}

const testHOC = {
  foo: function() {
    return { type: 'foo' }
  },
  bar: cacheValue(function() {
    // error TS2571: Object is of type 'unknown'.
    return { type: 'bar', foo: this.foo() }
  })
}

现在Typescript错误地将函数中的this类型标识为unknown,因此对this.foo()的调用是错误的:error TS2571: Object is of type 'unknown'.

有没有办法让它正常工作

  • 没有显式定义testHOC的类型(即编写接口),并且
  • 不使用箭头功能并直接引用testHOC(因为我以后可能要替换testHoc.foo)是

0 个答案:

没有答案