Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
Typescript Decorator on method; get method in decorator

I am trying to make a decorator that can:

  1. Take a parameter
  2. Store the method it is above as a callable function
  3. Map the callable function with the parameter the decorator takes.

Here is what I tried:

class Foo {

    static cachedMethods: Map<string, (arg: string) => void> = new Map();

    static decorator = (decoratorArg: string) => (
        target: Object, 
        propertyKey: string,
        descriptor: TypedPropertyDescriptor<any>
        ): any => Foo.cachedMethods.set(decoratorArg, target as (arg: string) => void);

}

class Bar {
   @Foo.decorator("some data")
   method1(arg: string) {
      console.log(arg);
   }

   @Foo.decorator("some other data")
   method2(arg: string) {
       console.log(arg);
   }
}

let func: Function = Foo.cachedMethods.get("some data")!;
func("hello world");

However, it says that func is not a function. It is storing it as the Bar class. How can I store the method as a function?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The target 1st argument that is received by the decorator function is actually the class prototype. So in your case it will be Bar prototype.

https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

  1. Either the constructor function of the class for a static member, or the prototype of the class for an instance member.
  2. The name of the member.
  3. The Property Descriptor for the member.

Since you want to store a reference to the method, you can use target[propertyKey] or descriptor.value

Playground Link

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda