A
A
Anton Shvets2019-12-16 13:46:10
typescript
Anton Shvets, 2019-12-16 13:46:10

How to make a decorator allowed only for methods of a given type?

there is a class

export interface IMyClass {
  requiredMethod(): void;
}

class MyClass implements IMyClass {
  @AppendHelix()
  method1(): string {
    return 'my-string';
  }

  @AppendHelix()
  method2(): number {
    return Number.EPSILON;
  }
  requiredMethod(): void { };
}

there is a decorator
export function AppendHelix(): MethodDecorator {
  return function AppendHelixDecorator<T>(
    target: any,
    propertyKey: string | symbol,
    descriptor: TypedPropertyDescriptor<T>
  ): TypedPropertyDescriptor<T> {
    const originMethod = target[propertyKey];
    return {
      value() {
         const origResult = originMethod.apply(this);
         return 'helix ' + origResult;
      },
    } as any as TypedPropertyDescriptor<T>;
  };
}

Goal: Describe decorator types in such a way that
@AppendHelix()
method2(): number {
  return Number.EPSILON;
}

caused a compilation error, i.e. so that the decorator can only be applied to methods with a certain signature, in this case returning a string

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-12-16
@Xuxicheta

T is just the signature of the method, put what you need there:

export function AppendHelix() {
  return function AppendHelixDecorator(
    target: any,
    propertyKey: string | symbol,
    descriptor: TypedPropertyDescriptor<() =>string>
  ) {
    const originMethod = target[propertyKey];
    return {
      value() {
         const origResult = originMethod.apply(this);
         return 'helix ' + origResult;
      },
    }
  };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question