Locate a class using an interface

Consider the code snippet below:

interface FirstInterface {}
interface SecondInterface {}
interface ThirdInterface {}

class TheClass {
  constructor(howdy: FirstInterface) {}
}

class Foo implements FirstInterface {}
class Bar implements SecondInterface {}
class Whatever implements ThirdInterface {}

[
  new Foo(),
  new Bar(),
  new Whatever()
].forEach(cls => {
  // How can I determine which class to inject into TheClass?
  // if(cls instanceof FirstInterface) doesn't work as expected :(
  new TheClass(cls);
});

I need to dynamically inject the correct class into TheClass, such as Foo.

Although interfaces are no longer accessible after compilation, is there a workaround for this issue?

My Dependency Injection (DI) Container automatically handles dependency injection, even with interfaces. However, when resolving classes that use interfaces in their constructors, it becomes challenging to determine the appropriate class without prior knowledge of the interface name.

Answer №1

Have you considered utilizing a discriminant property in your code? Take a look at this example:

interface FirstInterface {kind: 'firstInterface'}
interface SecondInterface {kind: 'secondInterface'}
interface ThirdInterface {kind: 'thirdInterface'}

class Foo implements FirstInterface {}
class Bar implements SecondInterface {}
class Whatever implements ThirdInterface {}

[
  new Foo(),
  new Bar(),
  new Whatever()
].forEach(cls => {
  // How do we determine which of the three classes to utilize here?
  if(cls.kind === 'firstInterface') new TheClass(cls);
});

You can experiment with this concept on the playground

Answer №2

In order to overcome this challenge, I made the decision to transition from interfaces to abstract classes. You can view my simplistic DI implementation on this link.

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

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

The Context API's `useContext` hook appears to be malfunctioning, persistently

My situation is as follows: export const LocationContext = createContext(null); export const LocationProvider = LocationContext.Provider; export const useLocationContext = () => useContext(LocationContext); Using the Provider: export const Search = () ...

Exploring the world of mocking tests using Jest and inputs

Is there a way to create a jest test specifically for this function? const input = require('prompt-sync')(); export function choices(): void { const choice = input("Choose a letter"); if (choice === "a") { con ...

Are auto-properties supported in TypeScript yet?

I've heard that properties in Typescript can be defined like they are in C# with automatic setters and getters. However, I have found it difficult to implement properties this way as the intellisense does not support such syntax in Typescript. I tried ...

The ReactDOM.createPortal modal has been successfully mounted onto the DOM, however, there seems to be no visible content

This project utilizes TypeScript and Next.js. Within it, there is a Modal component: interface ModalProps { onCancelModal: () => void; onAcceptModal: () => void; acceptEnabled: boolean; isLoading?: boolean; title: string; } const Modal: Re ...

Module for importing text without verifying types using wildcards

Here is a unique module definition using the wildcard character: declare module 'custom!*' { const data: string; export default data; } Check out how it's imported: import * as myData from 'custom!./myCustomData.txt'; B ...

Dexie is alerting us to a problem with a call that occurs before initialization

When setting up my application, I encountered an error related to the Courses Entity Class being called before initialization in my Dexie Database. Despite checking my code, I couldn't find any issues and there was no documentation available for this ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card. Typescript file icon: any; savedCreditCard = [ { cardExpiryDateFormat: "05/xx", cardNumberLast: "00xx", cardId: "x ...

Tips on troubleshooting the issue when attempting to use a hook in your code

I am trying to implement a hook to manage the states and event functions of my menus. However, when I try to import the click function in this component, I encounter the following error: "No overload matches this call. The first of two overloads, '(p ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...

Tips for managing numerous nested subscriptions

Looking to extract the id parameter from the route, fetch the corresponding task, and then its parent if applicable. Angular CLI: 7.1.4 Node: 11.6.0 OS: linux x64 Angular: 7.1.4 @angular-devkit/architect 0.11.4 @angula ...

Angular Material Table displaying real-time information

Recently, I've delved into Angular and have been experimenting with creating a dynamic table to showcase data. Currently, I have managed to get it partially working with static data. I drew inspiration from this particular example: https://stackblit ...