Typescript ClassDecorator 目标类型

Typescript ClassDecorator target type

我正在用打字稿编写自己的装饰器。目前,我的装饰器看起来像这样:

const Controller = (prefix = ''): ClassDecorator => (target: any): void => {
  // My Logic
};

export default Controller;

我的问题是关于 ClassDecorator 参数的。目前,我为 target 参数使用 any 类型,但我需要此参数的特定类型。所以我的问题是这个类型是怎么命名的?

我用谷歌搜索了一段时间,但一无所获。

您不需要显式声明控制器的 return 类型,因为编译器会推断它。只要您键入内部函数的参数..

type MyType = { foo: number }

function f() {
  console.log('f(): evaluated')
  return function (target: MyType) {
    console.log('f(): called' + target.foo)
  }
}

``

另一种方法是创建一个接口并让您的 class 实现它。

// 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 
}

现在创建您的class

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 
   }
}

我在class/method/accessor装饰器上使用这个,都通过了类型检查。


另一种使它更通用的方法是使用通用

这个例子来自我创建的库


export function Validate<T>(rules?: ValidatorRules) {
  return (target: T, propertyName: string): void => {
    // more code ... 
  }
}

上面的例子是一个接受规则的方法装饰器。

class YourApi {

    @Validate<YourApi>()
    myMethod(name: string, value: number) {
        // do your thing 
    }

}