【发布时间】:2017-07-25 14:50:51
【问题描述】:
我正在为react-tracking 编写环境声明。它公开了一个 track 装饰器,可以在类 和 方法上使用。
来自文档的简化示例:
import track from 'react-tracking'
@track({ page: 'FooPage' })
export default class FooPage extends React.Component {
@track({ action: 'click' })
handleClick = () => {
// ...
}
}
在我的环境声明文件中,我希望能够执行以下操作并让 TypeScript 选择正确的重载:
declare function track(trackingInfo?: any, options?: any): <T>(component: T) => T
declare function track(trackingInfo?: any, options?: any): any
export default track
虽然这对组件类很有效,但对于具有以下错误的方法却失败了:
[ts] Unable to resolve signature of method decorator when called as an expression.
查看 TS 为这个装饰器应用程序选择的类型表明它没有回退到应该匹配任何内容的签名,而是回退到组件类之一。
是否可以输入多态装饰器?如果是这样,我做错了什么?
更新:这是一个简化的简化示例。
第一个是单态的,按预期工作:
function trackClass(trackingInfo?: any, options?: any): ClassDecorator {
return null
}
function trackMethod(trackingInfo?: any, options?: any): MethodDecorator {
return null
}
@trackClass({})
class Foo {
@trackMethod({})
someMethod() {}
}
第二个例子是多态的,对两者都失败了:
function track(trackingInfo?: any, options?: any): ClassDecorator | MethodDecorator {
return null
}
@track({})
class Bar {
@track({})
someMethod() {}
}
【问题讨论】:
-
第二个例子不起作用,因为你有一个函数是
ClassDecorator | MethodDecorator- 你想说返回类型是ClassDecorator & MethodDecorator因为它会“做正确的事”装饰器被调用。
标签: typescript polymorphism decorator