Find the type constructor of each argument in a TypeScript constructor function

In my exploration, I have come across TypeScript libraries that, with just a simple annotation added to a class, can automatically inject that class into the constructor of another by specifying the argument type.

It works in a manner similar to this:

@someAnnotation()
class Foo {
}

@someAnnotation()
class Bar {
}

@someAnnotation()
class A {
    constructor(foo: Foo, bar: Bar) {
    }
}

@someAnnotation()
class B {
    constructor(a: A) {
    }
}

And seemingly out of nowhere, the library is able to extract these information

/// how do they get these? 
const constructorArgumentsTypesOfA = [Foo, Bar]
const constructorArgumentsTypesOfB = [A]

How does this all work? What is happening behind the scenes of that annotation code?

An exemplary library showcasing this capability is typedi

Answer №1

Upon examining the typedi source code, it was discovered that they implement a library named reflect-metadata

The implementation is as follows:

const paramTypes = Reflect.getMetadata('design:paramtypes', A);
console.log(paramTypes)

Specifically, the statement import 'reflect-metadata' needs to be invoked prior to any other actions.

In addition, a decorator is necessary. However, any decorator will suffice, including an empty function decorator.

function Service(target: any) {

}

Usage example:

@Service
class A {
    id = 'A'

    constructor(foo: Foo, bar: Bar) {
    }
}

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

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

What are some ways to access my AsyncStorage data from any location?

I am utilizing the saga library and storing tokens in AsyncStorage. My goal is to be able to freely access the token retrieved from AsyncStorage in both the loadUserPosts function and the loadPosts function. Where should I add async and how can I correct ...

The function db.query in Node.js isn't working as expected

Currently working with Node.js and Express, I am seeking to run queries on a MySQL database hosted on AWS EC2. In my db_connection.js file, I have established a connection to the database and attempted to export the connection (db) for use in other JavaSc ...

Updating the root URL in PhoneGap: A step-by-step guide

Is there a way to change the root URL of my application so that it loads my.com domain when it starts? I've tried changing the line below in config.xml but it doesn't seem to have any effect: <content src="index.html"/> ...

Retrieving user input from an angular controller function

I have a $resource object in Angular that looks like this: { _id: '1' items: [ {_id: 'a'}, {_id: 'b'}, {_id: 'c'} ] } My goal is to create a form with a checkbox for each element in the items array. In th ...

React fails to render within an Electron application

I've been attempting to execute some of the basic React examples within an Electron App, but I'm encountering an issue where nothing is displaying, despite the absence of any errors. Below is a snippet of the code: <!DOCTYPE html> <htm ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Is it possible to update the image source to display a hover image using the onmouseover property when converting Vue data to a for loop?

<li v-for="user in users" :key="user.id" class="nav-list" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave"> <router-link class="nav-link" :to="nameLowerCase(user.enName)"> <img :src="imgSrc(user)"> <p>{{user.enName}}& ...

Issue with security found: User permitted to insert custom JavaScript code (at runtime exclusively)

tag: As I develop a content generator, I've included objects that permit users to insert custom scripts onto the page. One issue troubling me is the preview feature of my plugin. While pages can't be saved in the preview, could allowing users t ...

Creating fundamental forms using HTML, CSS, and Javascript

I am tasked with creating a unique web application where users can sketch and annotate simple shapes. The purpose of the app is to create basic store maps. These shape drawings must be saved in a database, including their coordinates, sizes, labels, and cu ...

Navigating through asynchronous transactions in Node.js: A Guide

My application utilizes Nodejs, Mongodb, and amqp. The main module receives messages from amqp, processes them by saving message information into mongodb within a message transaction, and executes additional logic. function messageReceiverCallback(msg) { ...

When I attempt to complete a form on my Node.js Bot framework, I receive a warning: "WARN: IntentDialog - no intent handler found for

Just starting out with node.js and the bot framework. Created a form in json run in my bot, but encounter an error post form submission / - WARN: IntentDialog - no intent handler found for null Not sure why this happens. Using .addAttachment to display t ...

The troubleshooting guide for resolving issues with AngularJS data binding functionality

Exploring the world of AngularJS and encountering a minor setback with a basic example that seems to be refusing to load Angular. Within this particular example, there is a straightforward data binding test in which {{}} is utilized to display a hardcoded ...

Display endless data within a set window size

I am looking to create a fixed-size window for displaying text from the component <Message/>. If the text is longer, I want it to be scrollable within the fixed window size. See screenshot below: Screenshot export default function AllMessages(){ ...

Utilizing AngularJS to dynamically apply CSS classes based on the $index value

Is there a way to style my div based on the ng-repeat index, applying different styles for odd and even rows? The row with an even index should have all classes specified for the odd one plus additional classes. Controller: var odd = { 'class1&apos ...

Using Cucumber for testing javascript-loaded content can be incredibly powerful and effective in ensuring the functionality

As I develop my Rails application, I've decided to incorporate a combination of Test Driven Development and Behavioral Driven Development into my process. The challenge arises as my app utilizes the MochaUI web application user interface framework, w ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Difficulty in handling errors within an Express application

Hey there, I'm facing an issue with catching errors in my express.js application. The problem arises when the next function is called within the controller. For some reason, the error middleware does not execute as expected and I'm unsure why thi ...

Issue with moment library causing date to appear incorrect on 31st day

I am experiencing an issue when finding the difference between 2 dates in years. Specifically, when I choose the 31st date, it returns an invalid result as NaN. However, with other dates, the calculation displays the correct outcome. const selectedValu ...