Retrieving class reference from a Generic Argument in Typescript - how to do it?

I have developed a custom service provider that accepts a class as a parameter to retrieve an existing instance. I want to be able to use it like this:

class MyService{
   doSomething(){
      console.log("something");
   }
}

var myServiceInstance = serviceProvider.get<MyService>();
myServiceInstance.doSomething();

The issue is that currently I need to specify the class again when calling the get method:

serviceProvider.get<MyService>(MyService);

This seems inelegant. Is there a way to design the service provider interface so that the class reference can be internally retrieved based on the specified generic parameter?

Answer №1

Upon further exploration, I stumbled upon an effective solution that may vary slightly but eliminates the unattractive code:

class ServiceHandler{
   fetch<TService>(serviceClass:(new(...args)=>TService)):TService{
      return this._serviceList.get(serviceClass) as TService
   }
   private _serviceList = new Map<any,any>
}

This means I only need to mention the class reference once and can receive a typed outcome:

let customService = serviceHandler.fetch(CustomService);
customService.performTask();

If you have any alternative suggestions, please feel free to share.

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

Asserting a type null to undefined

Can anyone explain why TypeScript doesn't flag an error in this scenario, where null is assigned to a property expecting number or undefined? typescriptlang example type T1 = { value: number | null } type T2 = { value?: number }; const v1: T ...

Issue TS2315: Type 'ElementRef' does not support generics

While attempting to integrate @angular/materials into my application, I encountered a successful compilation with the following error messages: webpack: Compiled successfully. ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.t ...

The module 'node:fs' could not be located. Stack required:

I've been developing a Teams app with my tab in React and TypeScript. (In case you're unfamiliar, the tab can be seen as an individual React app) Currently, I'm setting up linting using ESLint and Prettier. I have successfully run the scri ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Automatically forwarding to another page in Angular 4 due to idle time

Is it possible to implement a timeout feature for inactivity on a webpage? For example, if a user is idle for 20 seconds without interacting with the page, can we automatically redirect them to the home screen? I've been struggling to get this functi ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

Issue with Three.js STL loader using TypeScript: Error message "Uncaught TypeError: Cannot read property 'XHRLoader' of undefined"

Having trouble loading an STL file into Three.js due to the three-stl-loader npm module not recognizing the THREE object. Here is the code snippet in question: import * as THREE from 'three' import * as THREESTLLoader from 'three-stl-loade ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

In TypeScript, it is definitely possible to infer complex types

I've encountered a rather intriguing problem that I'm struggling to solve. My goal is to develop a function that accepts an object of functions as input and returns an object with the same keys but a different return type, which depends on the v ...

Tips for Incorporating Material Design Lite into Angular2

I have encountered a minor issue while trying to incorporate material design into Angular2. I am using the latest version of Angular2, but the MDL framework seems to be incompatible. Here is what I have done so far: npm install material-design-lite --sav ...

Troubleshooting Firebase: How come my code is only accessing the initial document in my Collection?

After spending hours searching, I still can't find a solution to my problem with this code. The Firebase log file only shows: "after for each =undefinedsensor_location_1undefinedundefinedundefined " Why is it only referencing the first do ...

Combining 2 Observables in nestjs Interceptor: A Step-by-Step Guide

I am currently working on a NestJS interceptor to geolocate an address that is being sent through a REST API. Here is the code snippet: export class PointsInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): O ...

Customizing Angular tooltips based on specific conditions

Is it possible to implement a conditional tool tip? For instance, I am looking to only display the tool tip if cellData[id].length is greater than 120 within a div element. #solution <div matTooltip="Info about the action" class="{{cssCe ...

What is the best way to display data stored in local storage using React and Typescript?

Is there a way for the data to be displayed on the browser below the save button when I click save? My setup involves using React with a TypeScript template. function ButtonDefaultExample(props: IButtonExampleProps) { const { disabled, checked } = pro ...

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Using TypeScript variables within an SCSS file in Vue3 seems to be a challenging task

I'm currently working on a component that has the following template structure: <template> ... <ul class="circle-container"> <li v-for="img in images" :key="img"> <img :src="i ...

Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array? I attempted the following: const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll() .filter(landlinedRat ...

The anticipated data originates from the 'style' attribute, which is formally noted within the 'IntrinsicAttributes & TextInputProps & RefAttributes<TextInput>' type

I have been working on developing a text form using typescript within the React Native framework. To accomplish this, I created a TextInput component specifically designed for email and password inputs. Below is the code I have been working with: TextInpu ...

Only filter the array by its value if the value is specified

Is there a way to apply this filter while only checking each condition if the value is not undefined? For instance, if taxId is undefined, I would like to skip it rather than using it as a filter criterion. this.subAgencies = demoSubAgencies.filter(fun ...