How to Retrieve all Implementations of an Interface in Typescript

Is there a way in Typescript to retrieve a list of all classes that implement a specific interface?

In .Net, you can achieve this using reflection, but I haven't been able to find information on how to do the same in Typescript.

Here's an example of what I'm trying to accomplish:

interface IControlPanel { }
class BasicControlPanel implements IControlPanel { }
class AdvancedControlPanel implements IControlPanel { }
window.onload = () =>
{
    var controlPanels = IControlPanel.GetImplementations();
    for (var x = 0; x < controlPanels.length; x++)
    {
        document.write(controlPanels[x] + ", "); //outputs: BasicControlPanel, AdvancedControlPanel,
    }
};

It would be even better if these classes are easy to instantiate.

Answer №1

In the previous discussion, it was pointed out that TypeScript does not aim to generate JavaScript code that relies on the type system. This means that there won't be any runtime support for automatically achieving your desired functionality.

However, you can leverage TypeScript to maintain a collection of types in a manner similar to what you need. One approach could be using class decorators, such as:

interface IControlPanel {
  // define methods or attributes here
  doAThing(): void;
}

// create a registry for expected types
namespace IControlPanel {
  type Constructor<T> = {
    new(...args: any[]): T;
    readonly prototype: T;
  }
  const implementations: Constructor<IControlPanel>[] = [];
  export function GetImplementations(): Constructor<IControlPanel>[] {
    return implementations;
  }
  export function register<T extends Constructor<IControlPanel>>(ctor: T) {
    implementations.push(ctor);
    return ctor;
  }
}

Instead of explicitly stating that a class 'implements IControlPanel', you can now use the '@IControlPanel.register' decorator:

@IControlPanel.register
class BasicControlPanel {
  doAThing() { }
}

@IControlPanel.register
class AdvancedControlPanel {
  doAThing() { }
}

If you attempt to register a class that does not adhere to the IControlPanel interface, an error will occur:

// error, BadControlPanel is missing the required doAThing method
@IControlPanel.register
class BadControlPanel {
  doNothing() { }
}

You can now utilize the registry as needed, with some limitations:

window.onload = () => {
  var controlPanels = IControlPanel.GetImplementations();
  for (var x = 0; x < controlPanels.length; x++) {
    document.write(controlPanels[x].name + ", ");
    const panel = new controlPanels[x]();
    panel.doAThing();
  }
};

Although constructors are stored instead of strings as requested for instantiation, you can access the constructor's name property to get the string representation. Additionally, all classes must accept the same constructor argument types.
See Stackblitz example

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

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: https://i.sstatic.net/RW9ix.png I attempted to write code to achieve this, but the alignment ...

Sources of the TypeScript library in WebStorm

I'm brand new to TypeScript. I decided to use WebStorm because I'm familiar with JetBrains tools. In other programming languages, I'm used to having a workflow that includes some kind of dependency management system like Maven, which allows ...

Transforming an array into an object using TypeScript

I am attempting to create a generic type for a function that transforms an array into an object, like so: type ObjectType = { id: number; name: string; status: string }; const xyz: ObjectType[] = [ { id: 1, name: "X", status: " ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

Verify that each field in the form contains a distinct value

I have a formarray with nested formgroups. How do I ensure that the elements within each formgroup are unique? Here is an example of my form setup: form: FormGroup = this.formBuilder.group({ fields: this.formBuilder.array([]), }); private createField() ...

The presence of an Angular pipe is causing interference with the execution of a template

I've developed an application that can organize an array of objects in either ascending or descending order based on a specific property value using the custom function sortByField(). Additionally, the app allows users to filter data by entering a sea ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

My goal is to create a comprehensive collection of stories showcasing all Material UI components in React

Looking for a way to efficiently import all MUI components stories into my storybook. Is there a tool or repository available that can automate the generation of these stories, or perhaps has pre-written stories for all MUI components? I attempted to cre ...

Using ES modules with TypeScript, Webpack, and Jasmine: A comprehensive guide

My Package Workflow For my personal projects, I have a consistent structure for the packages I create and reuse. In production, I write these packages in TypeScript and compile them to JavaScript using `tsc` before publishing them to npm. This allows me t ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

Issue with accessing class property in events.subscribe in Ionic3

I am currently working on a class that listens for events. When the event is triggered, I need to add the data that accompanies it to an array and then display it. Here's what my class looks like: export class customClass { dataArray:Array<stri ...

Can you explain how to incorporate global functions from a javascript library into an Angular 2 project?

Recently I started working with angular-cli and came across a situation where I have an index.html containing a javascript script with some global functions. I want to access these functions in multiple parts of my application. As someone who is new to A ...

What is the significance of var-less variables in TypeScript class definitions?

Why is it that when creating a component class in Angular2, we don't need to use var when declaring a new variable? For example: @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> ` }) export class AppCo ...

How can I store an array of objects in a Couchbase database for a specific item without compromising the existing data?

Here is an example: { id:1, name:john, role:[ {name:boss, type:xyz}, {name:waiter, type:abc} ] } I am looking to append an array of objects to the existing "role" field without losing any other data. The new data should be added as individual ob ...

A guide on passing variables to the MUI styled function within ReactJS

Is it possible to pass a variable directly to the styled function in order to conditionally change style properties while using MUI styled function? I want to achieve something like this: borderColor: darkMode ? 'white' : 'black' const ...

The template is displaying the string as "[object Object]"

I've implemented code in my ngOnInit function to fetch the translation for a specific text. The following function is being called: async getEmailTranslation() { const email$ = this.translate.get('SUPPORT_TRANSLATE.EMAIL'); this.emai ...

Looking for a TypeScript annotation that allows accessing an object property using a variable

When working with plain JavaScript, we have the ability to access an object's property value using a variable. For example, this is permitted: let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() }; let prop = 'b'; c ...