Specify typing for a class when passing it as a function parameter

Initially, let's take a look at the central Interface :

// IMySuperInterface.interface.ts

export interface IMySuperInterface<T = any> {
  handle(arg?: any): Promise<T>;
}

Essentially, what I require is a shared type for ==> child classes with a 'handle' function. Something along the lines of :

function MyDummyFunction (param: {{class that extends IMySuperInterface)}})

I am attempting to enlist all classes in my application that implement my 'IMySyperInterface'

// MySuperImplementation.service.ts
@Feature('ReferenceA')
export class MySuperImplementation
  implements IMySuperInterface {

 constructor(private readonly logger: myLoggerService) {
    this.logger.setContext(this);
  }

  async handle(someDummy: any): Promise<void> {
    ....
  }
}

And here is the definition of the Decorator

// feature.decorator.ts
const _mapping = new Map<string, anyOrIdontKnowWhatToDo>();

export function Feature(key: string) {

  return function (target: **HERE WHAT CAN I WRITE  ??????**) {
    Feature.cache.set(key, target);
    return target;
  };
}

I am trying to find some kind of 'AtLeastContains<IMySuperInterface>' or Type<IMySuperInterface>

with

export interface Type<T = any> extends Function {
    new (...args: any[]): T;
}

However, I encounter:

  • neither : sorry but 'prototype' is missing in IMySuperInterface
  • neither : sorry but logger is not compatible with 'Type' type

I am confused :(.. How can I declare as a parameter of my function a Class that implements my Interface? Note: The argument in the constructor of my class changes constantly and so does the argument of the function in the interface.

Answer №1

Today, I discovered a new way to apply decorators specifically to classes. I successfully implemented it with the following code snippet:

export function CustomDecorator(
  options: MetadataOptions,
): <TFunction extends RunnerClass>(target: TFunction) => void | TFunction {
  return (target) => {
    Reflect.defineMetadata(CustomMeta, options, target);
    return target;
  };
}

This custom decorator is fully typed, providing precise control over the generic type of the target. It offers flexibility in setting up your own interface and executing the desired logic within the decorator.

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

Mastering the art of typing queries in ReactQuery with Typescript

Hey there, can someone help me with this TypeScript error? https://i.sstatic.net/4Zn39.png https://i.sstatic.net/NTxAa.png https://i.sstatic.net/fiN87.png https://i.sstatic.net/CTd4u.png ...

"Encountering the error of 'require is not defined' in an Electron-React-Webpack-Typescript application when utilizing

When I add these lines to /src/renderer.ts in an Electron-React-Webpack-Typescript app: ipcRenderer.on('messageFromMain', (event, message) => { console.log(`This is the message from the second window sent via main: ${message}`); }); I encou ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

Is it possible to store the reference of a class in a variable so that it can be instantiated at a later time?

My goal is to ensure that a class implements a method called okClick, so I decided to use an interface. interface BaseComponent { okClick(): void } I then created a class that implements this interface. class ComponentImplementation implements BaseCompo ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Closing a bootbox alert by clicking on a href link

Utilizing bootbox alert within my Angular2 application to present information to users on the UI. The alert message includes href links, and I want the page to navigate to the clicked link while also closing the bootbox modal. However, I am facing an issue ...

unanticipated installation issue with published npm package on verdaccio

I am on a mission to create and release a package containing commonly used TypeScript functions on Verdaccio, an npm registry that operates on Docker. After completing the build for my TypeScript package, this is how my project structure looks: https://i ...

Retrieving the Angular API response from a service and passing it to a component

One challenge I encountered in my Angular 12 application is capturing the response of an API call made in the service file within my component. The issue arises from the asynchronous nature of the API response, which causes the console to always display &a ...

Angular 5 TypeScript's key value data structure

I am in search of a way to replicate the functionality of a key/value dictionary in Python. My project is utilizing Angular 5 typescript, and I am still exploring the available data types. The ever-changing nature of Angular has made it challenging due to ...

Issue with accessing custom method in subclass in Typescript

Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class. export class MyError extends Error { public code: number; constructor(code: number, message?: string) { super(mes ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Angular: ngModelChange not updating value in dropdown menu

I have successfully implemented a dropdown feature like this: <select (ngModelChange)="onChange($event)"> <option *ngFor="let quantity of quantities" [ngValue]="quantity"> {{ quantity }} ...

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

When using `onClick` in React, the old state value is not captured even though it may appear to be

In order to enhance the modularity and generality of my tabs and tab slots, I have developed a somewhat intricate setup. To achieve this, I opted to create a context and provider that expose methods for manipulating tabs and slots (where slots represent wh ...

Tips for incorporating a reference into a styled component div in a React application using TypeScript

Looking to include a reference to a styled component div. Here is the code snippet: const DragAndDrop: React.FC<any> = props => { const divRef= React.createRef(); return ( <Zone ref={divRef}/> ); } Encountering thi ...

Can we classify an array as a data type?

Can an array be considered a data type, or is it more accurately described as a pointer to its first element? ...

Discovering a locator based on the initial portion of its value

Here's a piece of code that is used to click on a specific locator: await page.locator('#react-select-4-option-0').click(); Is there a way to click on a locator based on only the initial part of the code, like this: await page.locator(&apos ...