utilizing reflect-metadata to retrieve the decorators placed on an object

There's a unique decorator in my code that seems to have no functionality:

export function myDecorator(target: any, key: string) {
   var t = Reflect.getMetadata("design:type", target, key);
}

This decorator is being used with properties of a class:

export class SomeClass {

    @globalVariable
    someProperty: string;

    @globalVariable
    fakeProperty: number;
}

What I want to achieve now is to retrieve all properties of the class that have been decorated with @globalVariable.

I attempted to use "reflect-metadata" with:

Reflect.getMetadata('globalVariable', this);

However, the result is always "undefined". Is there a way to achieve this using reflect-metadata or am I misunderstanding something?

Answer №1

Once a class is defined, property decorators are invoked for each property definition inside the class.

For example, if you decorate properties in SomeClass with @myDecorator:

export class SomeClass {
    @myDecorator
    someProperty: string;
}

The myDecorator function will receive:

target: (the definition of SomeClass)
key: (the name of the property)

By enabling metadata through the "emitDecoratorMetadata" property, the TypeScript compiler will produce metadata properties:

'design:type', 'design:paramtypes', and 'design:returntype'.

This enables the use of Reflect.getMetadata with these keys:

Reflect.getMetadata('design:type', ...)
Reflect.getMetadata('design:paramtypes',...)
Reflect.getMetadata('design:returntype', ...)

It's important to note that Reflect.getMetadata cannot be used with the decorator name.

Answer №2

To achieve the desired outcome, you must implement the globalVariable function in the following manner:

function globalVariable(target: any, propertyKey: string | Symbol): void {
    let variables = Reflect.getOwnMetadata("globalVariable", target.constructor) || [];
    variables.push(propertyKey);
    Reflect.defineMetadata("globalVariable", variables, target.constructor);
}

Then, during runtime, you will be able to invoke

Reflect.getMetadata('globalVariable', this);

as per your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loading a webpack bundled ngModule dynamically to handle a route efficiently

In an effort to make working on our large frontend projects more manageable, we are looking to split them into multiple independently deployed projects. I am attempting to integrate a bundled ngModule to handle a route from within another app. It is crucia ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Is there a way to transform Observable<Observable<Organization>[]> into Observable<Organization[]>?

I have implemented ngrx/store in my project. .map((p: Observable<Organization>[]) => { return new usersActions.GetOrganizationSuccess(p); }) The GetOrganizationSuccess action is designed to accept Organization[] as the payload. Is ...

Tips for managing an array of observable items

In my current project, I am working with an Angular application that receives a collection from Firebase (Observable<any[]>). For each element in this collection, I need to create a new object by combining the original value with information from ano ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Using Typescript, develop a function within an entity to verify the value of a property

In my Angular 7 app, I have an entity defined in my typescript file as follows: export class FeedbackType { id: number; name: String; } I am looking to create a function within this entity that checks the value of a property. For example: feedba ...

Implementing TypeScript/Angular client generation using Swagger/OpenAPI in the build pipeline

Generating Java/Spring Server-Stubs with swagger-codegen-maven-plugin In my Spring Boot Java project, I utilize the swagger-codegen-maven-plugin to automatically generate the server stubs for Spring MVC controller interfaces from my Swagger 2.0 api.yml fi ...

Fastest method to invoke a potentially undefined function

With a background in C#, I am familiar with the null-conditional operator which allows you to call a function while avoiding a potential null-reference exception like this: Func<int> someFunc = null; int? someInteger = someFunc?.Invoke(); // someInte ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Utilizing a component from a different module

Currently working on Angular 4 and facing an issue with referencing a component from another module. In my EngagementModule, the setup is defined as below: import { NgModule } from '@angular/core'; // other imports... @NgModule({ imports: [ ...

Using TypeScript with Vue allows you to customize the default export of Vue

Currently experimenting with Vue and TypeScript, attempting to compile to AMD in my tsconfig file. The type definition in vue/types/index.d.ts for Vue.js includes: export default Vue; However, this results in TypeScript compiling it like this: import V ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

Having trouble locating the type definition file for 'cucumber' when using the Protractor framework with Cucumber and Typescript

Currently immersed in working on Protractor with Cucumber and TypeScript, encountering a persistent issue. How can the following error be resolved: Cannot locate the type definition file for 'cucumber'. The file exists within the pr ...

Unable to export data from a TypeScript module in Visual Studio 2015 combined with Node.js

Within one file, I have the code snippet export class Foo{}. In another file: import {Foo} from "./module.ts"; var foo: Foo = new Foo(); However, when attempting to run this, I encountered the following error: (function (exports, require, module, __file ...

Saving a picture to your Ionic device

I am currently using the code snippet below to access the device's Photo Library. However, it is returning a base64 encoded string, which has left me feeling unsure of how to proceed with this information. My goal is to save the photo to the applicati ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...