当我在对象文字中定义函数时,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
)是