Using Typescript to assign static metadata to a class for runtime retrieval

Could someone demonstrate how to create a custom decorator in Typescript that adds static metadata to the type, allowing for runtime access without needing to instantiate an instance of the class? I'm looking for something similar to __annotations__ in Angular.

Update - Please refer to the image below. How can I develop my own decorator factory that works on the type itself rather than just modifying instances?

https://i.sstatic.net/odTbI.png

Answer №1

After some exploration, I have figured this out. Coming from a background in .net, I failed to realize that the target/class can be treated like any other javascript object. The constructor appears to be just another specialized method on the object.

export function MyDecorator(metadata: any) {
  return (target) => {
    if (!target[`__my_annotations__`]) {
      target[`__my_annotations__`] = {};
    }

    target[`__my_annotations__`].metadata = metadata;

    return target;
  };
}

This solution works well for me, and I hope it helps someone else save time on this issue.

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

What is the best method for retrieving a single resource from the backend using Typescript and createAsyncThunk by obtaining the params ID?

I am currently facing an issue while trying to fetch a single resource (one to-do) from my backend. I am struggling to set up my store in the frontend and cannot seem to find the req.params.id as I would typically do with regular Javascript + Redux thunks. ...

Querying Angular/Firestore for a collection document to extract a single field from each document and store them in an array

I am currently querying my collection of documents and attempting to extract only the phone numbers into an array. The goal is to store the phone numbers in an array for use by another function. While the Firebase documentation provides examples using co ...

Angular Date format

When I retrieve a date value from my angular interface, it appears in the following format. Sat Dec 29 2018 08:42:06 GMT+0400 (Gulf Standard Time) However, when I receive the data from an API, the JSON result looks like this. How can I make it the same t ...

Problem: Unable to open Angular href links on IOS devices

I am experiencing an issue with a shared-code application in Android and IOS. The link successfully opens on an Android device but fails to open on an IOS device. Are there any differences between the two platforms that could be causing this discrepancy? ...

Angular - Dropdown menu fails to display options

I encountered an issue with the JSON response from my Angular-12 API endpoint: { "message": "vehicle Model Detail.", "error": false, "code": 200, "results": { "vehiclemakes": [{ ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data: { "Stations": { "44": { "NAME": "Station 1", "BRANCH_CD": "3", "BRANCH": "Bay Branch" }, "137": { "NAME": "Station 2", ...

Mastering error handling in Angular's Http requests

In my frontend application using Angular, I need to communicate with a RESTful webservice for the login process. The webservice returns different response codes in JSON format depending on the success or failure of the login attempt: If the login is corre ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Using Angular, Typescript, and ngxs to manage state observables, one may wonder what exactly a variable ending with an exclamation mark (!) signifies. An example of this can be seen in the following code snippet:

Within my TS file, a declaration is present: import { Select } from '@ngxs/store'; @Injectable() export class someService { @Select(someSELECTOR) varName$!: Observable<someType[]>; elements$ = this.varName$.pipe( map(elements => e ...

When utilizing HttpParams in Angular 2 for an HTTP GET request, a 404 error is returned

I seem to be having a trouble with calling a GET endpoint from an Angular UI. I am trying to pass a timestamp as a parameter to the endpoint. Initially, I approached it in a basic way: return this.http.get(this.Uri + academyId + "?dateWhenToCalcula ...

Angular 2.0 in conjunction with D3.js does not style SVG elements using CSS

Currently, I am utilizing Angular 2.0 TypeScript along with the d3.js library to create graphics. My main focus is on applying CSS to the axis (especially shape-rendering: crispEdges;). Do you have any suggestions? Check out the code below: var vis = d3 ...

Unable to create the editor within Angular framework

I'm in the process of developing a code editor There's a component that is rendered conditionally <ace-editor [(text)]="text" #editor style="height:150px;"></ace-editor> Within the ngAfterViewInit Lifecycle hook ...

Setting up React-Native using Yarn and Typescript: A comprehensive guide

After working on my project with basic react-native and npm, I encountered a problem when needing to add a new feature at a later stage. This led me to the decision of restarting the build in order to fix coding mistakes and errors. For this fresh start, ...

"This error message states that the use of an import statement outside a module is not allowed

After searching for a solution without any luck, I decided to start a new discussion on this topic. Currently, I am working on azure functions using Typescript and encountering the following error: import { Entity, BaseEntity, PrimaryColumn, Column, Many ...

Error: The package name "@angular/compiler" is not valid in Npm

After successfully installing Ionic2 for a new project, I proceeded to set up a continuous integration build. However, running npm install on the build server resulted in failure with the following error: npm ERR! Windows_NT 6.2.9200 npm ERR! argv "C:&bso ...

Filter the JSON data within every mat-tab section

Can someone help me with displaying the data from these JSON objects? [ { "defectClassification": "Wrong Color", "sample": 0, "defect": "CRITICAL" }, { "defectClassification": "Delamination", "sample": 0, ...

What is the method for copying table data, including input text as cells, to the clipboard without using jQuery?

I have a basic table that looks like this: <table> <thead> <tr> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>Savings <button type="button" (click)=" ...

Can you assign a HostListener to a particular button in Angular application?

Whenever the ESC key is pressed, I want to invoke a specific method. This is how I currently have it set up: @HostListener('window:keydown', ['$event']) clickEscape(event: KeyboardEvent) { //if ESC was pressed if(event.keyCode ...

Generate a versatile Union type featuring a mapped property

I am currently working with different types of data enum DataTypes { Email = 'email', Checkbox = 'checkbox', } type DataTypeValues = { [DataTypes.Email]: string; [DataTypes.Checkbox]: boolean; }; type Type1<T extends DataTy ...