Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
How to use Reflection in typescript similarly like in java?

I'm using reflection in Java to obtain some information from the TestNG annotation like in the code snippet below:

Reflections reflections = new Reflections("", new MethodAnnotationsScanner())
Set<Method> annotated = reflections.getMethodsAnnotatedWith(Test.class)

Currently, I have a jest framework with a jest-decorated plugin to help in using annotations.

How I can replicate the same reflection method in Java but in typescript to collect this information from the annotations?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Please take a look at Typescript's Decorators + Reflect Metadata API, which can also be enabled for TS compiler. It doesn't work exactly as Java, but you still can collect required information about annotated entities. Small example of how to collect annotated classes:

const myTypes: any[] = []

@annotation
class MyClass {
  type = "report";
  title: string;
 
  constructor(t: string) {
    this.title = t;
  }
}

function annotation(constructor: Function) {
    myTypes.push(constructor)
}

console.log('All annotated classes', myTypes);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try tst-reflect. It is pretty advanced Reflection system for TypeScript (using custom typescript transformer plugin).

This should be equivalent of your Java code:

import {
    reflect,
    Type
} from "tst-reflect";

// Some decorator...
function test(_, __)
{
}

@reflect()
class A
{
    @test
    foo()
    {
        return 0;
    }

    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class B
{
    @test
    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class C
{
    baz()
    {
        return "lorem ipsum";
    }
}

const decoratedMethods = Type.getTypes()
    .flatMap(type => type.getMethods().map(method => ({ method, type })))
    .filter(entry => entry.method.getDecorators().some(decorator => decorator.name == "test"));

for (let entry of decoratedMethods)
{
    console.log(entry.method.name, "in", entry.type.name);
}

Output

foo in A
bar in B

Check Synopsis. You are able to create instances of those types (even they are from different files) and call those methods. Also those decorators can have arguments so you will be able to filter methods with same decorators but different arguments.

tst-reflect is still in development so the global look ups of types require those @reflect decorators or custom decorators with @reflect JSDoc tag; reason is size optimization of the generated metadata. But there is an issue to extend configuration by "include" glob patterns which will include all types from all the modules matched by that globs.

PS: Check out configuration wiki and use this configuration:

tsconfig.json

{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    },
    // ADD THIS!
    "reflection": {
        "metadata": {
            "type": "typelib" // this mode will generate and auto-import library with generated reflection metadata
        }
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda