Is there a way to access the name of a generic type T class in TypeScript?

I'm currently working on incorporating the Service Locator pattern into my TypeScript project.

Below is the snippet of my code:

 //due to only partial knowledge of TypeScript
  private static serviceMap: Map<string, any>;

  public static get<T>(): T {
    // firstly lazily register all of the necessary services if this is the
    // first time calling get.
    if(this.serviceMap == undefined){
      this.init();
    }
    let service = this.serviceMap.get(T.name) //issue
    if(service == undefined){
      throw Error("You must register the service before retrieving it.")
    }
    return service;
  }

The line marked as an issue is causing a problem. I'm attempting to fetch the class type name passed to the method. However, when trying to retrieve T.name, I encounter this error:

TS2693: 'T' only refers to a type, but is being used as a value here.

Is there a way to obtain the name of the class of type T?

As I'm relatively new to TypeScript, I apologize if the solution is straightforward.

Answer №1

When using the Service Locator pattern, the get method must receive a parameter that helps to locate the specific instance.

By changing the method signature to:

public static get<T>(fn: Function): T {

You can access the name property of the function type inside the get method like this:

let service = Locator.serviceMap.get(fn.name);

To retrieve class instances using the locator, you can call:

const classInstance = Locator.get<ClassC>(ClassC);

For a working example, you can check out this stackblitz.

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

The Joi validate() function will return a Promise instead of a value when used within an asynchronous function

Trying to understand how async functions and the Joi.validate() function behave. Below is a function used for validating user input. const Joi = require("joi"); const inputJoiSchema= Joi.object().keys({ name: Joi.string(), email: Joi.string().require ...

The specific property 'splice' cannot be found within type 'T'

As I delve into working with TypeScript, an unexpected error arises: Property 'splice' does not exist on type 'T'. type Item = { name: string, body: string, imgOne: string, imgTwo: string, }[] // Another file contains this func ...

using javascript to create two choices

I am facing a small complication between two select options in my javascript code. Here is the snippet of my javascript: function displayVals() { var singleValues = $("select option:selected").text(); //to stay selected $("#hiddenselect").val(s ...

Experiencing a problem in AngularJS 2 after including 'routing' in the imports section of app.module.ts

An issue arises when I include 'routing' in the imports section of app.module.ts app/app.routing.ts(18,23): error TS2304: Cannot find name 'ModuleWithProvider'. [0] app/app.routing.ts(18,65): error TS2304: Cannot find name 'AppRou ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

Issues with implementing Bootstrap tabs in Vue application

Currently, I am in the process of developing an application using vue, vue-router, and bootstrap. My goal is to integrate tags in bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-l ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Error encountered when parsing JSON data in Vue.js due to presence of invalid characters in the

I have been working on a web application that allows me to upload a JSON file, make changes to it, and then download it. However, the resulting JSON is not valid because certain characters seem to change during the process. Even when I simply upload and do ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Why is it necessary to define a property outside the constructor in Typescript, when in Javascript I wouldn't have to do that?

When working with Javascript, creating a class like the one below allows us to avoid declaring and initializing a property named logs outside of the constructor: class Logger { constructor() { this.logs = []; } } However, transitioning to TypeScri ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: https://i.sstatic.net/YzJ4E.png I have data in a model that indicates the ...

Displaying a MySQL blob image in an HTML file with Vue.js: A step-by-step guide

Here is a Vue file that I have: export default { data(){ return{ info: { name: '', image: '', }, errors: [] } }, created: function(){ thi ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Implementing authentication using http.post in Angular 2 with Django-Rest-Framework

I have spent more time than I care to admit trying to find a solution to this particular issue, but unfortunately, I am unable to resolve it on my own. Currently, I have a Django-rest-api that I set up using this tutorial. I can successfully interact with ...

so many alerts to choose from aside from jsx/react

After some consideration, I believed I had devised an effective way to notify users when the array is empty and there's nothing to display. However, upon implementation, I realized my technique only works onFocus or page reload because I placed the fu ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

Regular Expression - Locate all numerical values within text formatted with HTML

I am attempting to locate all the numbers within an HTML document. However, I want to ensure that I exclude numbers that are part of a word, such as "o365", "high5", and similar instances. Here is my current approach, but it does not successfully avoid w ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...