Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities.

My goal is to pass the "register" method an abstract class type along with an instance of a derived type.

In the "resolve" function, I aim to provide an abstract class type as input and receive a typed instance that was passed in the "register" method.

How should I define the type for the "instance" parameter in the "register" function? Although I successfully implemented correct type checking for the "resolve" method, the technique using "{prototype: T}" does not seem to work for the "register" method.

const _items = new Map();

export class IoC {
    public static register<K>(service: K, instance: any) {
        _items.set(service, instance);
    }
    public static resolve<T>(service: {prototype: T}): T {
        return _items.get(service);
    }
}

// example of usage
IoC.register(AppServer, new TestAppServer());
IoC.resolve(AppServer) 

Answer №1

This is the final result I came up with.

const _elements = new Map();

export class DependencyInjector {
    public static register<T>(service: {prototype: T}, instance: T) {
        _elements.set(service, instance);
    }
    public static resolve<T>(service: {prototype: T}): T {
        return _elements.get(service);
    }
} 

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

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Watching - transforming / combining

I am a beginner when it comes to working with Observables. Here's the Effect that I am using: My goal is to dispatch the PositionUpdateAction or PositionFailedAction before the SunriseSunsetAction is dispatched. Currently, what happens is that the r ...

React: Using useState and useEffect to dynamically gather a real-time collection of 10 items

When I type a keystroke, I want to retrieve 10 usernames. Currently, I only get a username back if it exactly matches a username in the jsonplaceholder list. For example, if I type "Karia", nothing shows up until I type "Karianne". What I'm looking f ...

The format must be provided when converting a Spanish date to a moment object

I am working on an Angular 5 project where I am converting dates to moment objects using the following code: moment(date).add(1, 'd').toDate() When dealing with Spanish locale and a date string like '31/7/2018', the moment(date) funct ...

Encountering an error with the Next Auth adapter in TypeScript when attempting to modify the default User interface

This is my first time using TypeScript and I am attempting to customize the default User interface for next-auth. I have experimented with the following code: next-auth.d.ts import { User } from "next-auth" import { JWT } from "next-auth/j ...

Typescript and Visual Studio Code Issue: Module "myimage.png" Not Found

I am encountering an issue where VS Code is complaining about not being able to find a module when trying to import an image from an assets directory within my project. Despite the fact that the image import works fine, I keep receiving the error message: ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

Changing the Image Source in HTML with the Power of Angular2

Despite my efforts, I'm unable to display the updated image in my HTML file. In my TypeScript file, the imageUrl is updating as expected and I've verified this in the console. However, the HTML file is not reflecting these changes. In my researc ...

Managing dates in my Angular 2 application using Typescript

Currently, I am in the process of generating test data for my views before initiating API calls to the API application. Within a service in my Angular 2 application, I have defined an interface as follows: export interface amendmentBookings { booking ...

Importing Angular Material modules

I've integrated the Angular Material module into my project by updating the material.module.ts file with the following imports: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatT ...

The Typescript code manages to compile despite the potential issue with the type

In my coding example, I have created a Try type to represent results. The Failure type encompasses all possible failures, with 'Incorrect' not being one of them. Despite this, I have included Incorrect as a potential Failure. type Attempt<T, ...

Differentiate between function and object types using an enum member

I'm currently experimenting with TypeScript to achieve narrowed types when dealing with index signatures and union types without explicitly discriminating them, such as using a switch case statement. The issue arises in the code snippet below when at ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Is it possible to initialize multiple Observables/Promises synchronously in ngOnInit()?

I am relatively new to Angular/Typescript and facing a challenge. In my ngOnInit(), I am trying to fetch settings from my backend using a GET request. After that, I need to subscribe to an observable. The observable updates the widgets' content over t ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

Filtering a multi-dimensional array in Ionic 3

I attempted to filter an array from a JSON with the following structure {ID: "2031", title: "title 1", image: "http://wwwsite.com/im.jpg", url: "url...", Goal: "3000000", …} The array is named 'loadedprojects' and below is the filteri ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...