Closed3

TypeScript の MethodDecorator メモ

odanodan

型定義

declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
odanodan

基本形
https://stackoverflow.com/questions/56189503/how-to-use-a-typescript-method-decorator-and-retain-normal-this-scope

export function Decorator(): MethodDecorator {
  return (
    target: any,
    methodName: string | symbol,
    descriptor: TypedPropertyDescriptor<any>,
  ) => {
    // デコレータを付与したメソッド
    const originalMethod = descriptor.value;

    console.log({ target, methodName, descriptor });
    descriptor.value = function (...args: any[]) {
      // 引数
      console.log({ args });
      const result = originalMethod.apply(this, args);
      return result;
    };
  };
}
odanodan

メソッドのラップをするときはメタデータや名前をコピーして置くのがいいっぽい?
ref: https://github.com/odavid/typeorm-transactional-cls-hooked/blob/c16e19f1727e3e55832848a4e135cc19fb7160fb/src/Transactional.ts

    Reflect.getMetadataKeys(originalMethod).forEach(previousMetadataKey => {
      const previousMetadata = Reflect.getMetadata(previousMetadataKey, originalMethod)
      Reflect.defineMetadata(previousMetadataKey, previousMetadata, descriptor.value)
    })

    Object.defineProperty(descriptor.value, 'name', { value: originalMethod.name, writable: false })
このスクラップは3ヶ月前にクローズされました