【问题标题】:Typescript ClassDecorator target typeTypescript ClassDecorator 目标类型
【发布时间】:2020-05-04 18:48:50
【问题描述】:
我正在用 typescript 编写自己的装饰器。目前,我的装饰器看起来像这样:
const Controller = (prefix = ''): ClassDecorator => (target: any): void => {
// My Logic
};
export default Controller;
我的问题是关于 ClassDecorator 参数。目前,我对target 参数使用any 类型,但我需要为该参数指定一个特定类型。所以我的问题是这种类型是如何命名的?
我用谷歌搜索了一段时间,但没有找到任何相关信息。
【问题讨论】:
标签:
typescript
decorator
typescript-decorator
【解决方案1】:
您不需要显式声明 Controller 的返回类型,因为编译器会推断它。只要您键入内部函数的参数..
type MyType = { foo: number }
function f() {
console.log('f(): evaluated')
return function (target: MyType) {
console.log('f(): called' + target.foo)
}
}
``
【解决方案2】:
另一种方法是创建一个接口并让您的类实现它。
// interface.ts
export interface ExampleInterface {
// just some method that is going to get use
start(): void
stop(): void
}
然后在你的装饰器中
import { ExampleInterface } from 'interface'
export function ExampleDecorator(target: ExampleInterface ) {
// do things with your decorator
}
现在创建你的类
import { ExampleInterface } from 'interface'
import { ExampleDecorator } from 'decorator'
@ExampleDecorator
export class ExampleClass implements ExampleInterface {
start(): void {
// do your start thing
}
stop(): void {
// do your stop thing
}
someOtherMethod() {
// do some other thing
}
set someSetter(value: string) {
// set some other value
}
}
我在类/方法/访问器装饰器上使用这个,都通过了类型检查