typescript what type of functionality do dynamic class methods provide

I'm currently working on building a class that creates dynamic methods during the constructor stage. While everything is functioning properly, I've encountered an issue with VS Code's auto suggestion not recognizing these dynamic methods. How can this be resolved? Here is the codeSandBox.

I've attempted using an interface, but still no luck.

export default class A {
  private version = 1;
  get getVersion() {
    return this.version;
  }
  private actions = ["approve", "edit", "delete"];
  constructor() {
    this.actions.forEach(
      method =>
        (A.prototype[method] = route => {
          console.warn(method + " called");
        })
    );
  }
}

const B = new A();
console.warn(B.getVersion);
console.warn(B.approve()) // Auto suggestion not available here  

Answer №1

While it is possible to achieve this, the method is quite unconventional. Using meta programming in this manner makes it difficult to conduct thorough type checking. You can experiment with a potential solution by visiting this playground.

To start, you must declare "actions" as an unchangeable array in TypeScript for better typing.

private actions = ["approve", "edit", "delete"] as const;

Then, formulate a mapped type that defines the modifications made to the type by your "forEach" method.

type _A = {
    [K in A['actions'][number]]: (route: string) => void
}

It's crucial for this to be a type and not an interface.

Lastly, extend an interface that incorporates this type alias. Surprisingly, TypeScript does not raise any issues related to circularity at this point.

export default interface A extends _A {
}

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

JavaScript Datepicker Formatting

I need to modify the date format of a datepicker. Currently, it displays dates in MM/DD/YYYY format but I want them to be in DD-MM-YYYY format. <input id="single-date-picker" type="text" class="form-control"> Here's the JavaScript code: $("# ...

Tips on swapping out a part in ExtJS

Currently, my ExtJS window features a toolbar at the top and loads with a plain Panel at the bottom containing plain HTML. Everything is working smoothly in this setup. However, I now wish to replace this bottom panel (referred to as 'content') w ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

Can you provide the syntax for a generic type parameter placed in front of a function type declaration?

While reviewing a project code recently, I came across some declarations in TypeScript that were unfamiliar to me: export interface SomeInterface<T> { <R>(paths: string[]): Observable<R>; <R>(Fn: (state: T) => R): Observable ...

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...

An issue in Node.js NPM PDFkit arises when generating PDF tables with Voilab pdf table, leading to paragraph errors in the resulting

Greetings everyone, I appreciate you taking the time to visit. I am currently facing some challenges with Voilab PDF Kit, a library for PDFkit that is designed to assist in organizing tables for NPM Pdfkit. After successfully generating a table, I attemp ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

The loading indicator fails to show up when users navigate between pages that have already been loaded in NextJS and ReactJS

What do I need: I am seeking a way to show a loading indicator whenever a user switches between pages on my website. After discovering an effective example at https://github.com/zeit/next.js/tree/canary/examples/with-loading, I implemented a similar appro ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Unable to show an image within the <div> element when hovering the mouse

Is it necessary to use the background style image in order to display an image on mouseover of a name? I have implemented a controller and would like the image to be replaced by text within a div tag. Below is my HTML code: <!DOCTYPE html> <html& ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

When navigating back, the Bootstrap Multistep Form breaks down

Tools I'm currently utilizing: HTML, CSS, Javascript, Bootstrap 3 Library / Package in use: https://codepen.io/designify-me/pen/qrJWpG Hello there! I am attempting to customize a Codepen-based Bootstrap Multistep Form from the provided link abov ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

Creating a seamless navigation experience with Next.js: Implementing per-page layouts for efficient 2-link navigation on a single screen

In my next.js project, I have a URL like "http://localhost:3000/forum". If a user goes to "http://localhost:3000/forum/{postId}", I want to redirect them back to "http://localhost:3000/forum" My folder structure is in the 'App' directory and I h ...

What could be causing the reliability issue with this particular Angular JS code for dropdown menus?

Attempting to create a dynamic country-city dropdown menu using AngularJS <div> Country: </br> <select data-ng-model="country" ng-options="country.name for country in countries" data-ng-change="updateCountry(country) ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...