What is the best way to design an interface in TypeScript that accepts a class as a parameter, rather than an instance of the class?

I am looking to develop an interface that can receive an actual class instead of an instance of the class. Here is a sample code snippet:

class CheckIfGoNextPage{
  localResult;
  next;
  constructor(localResult:string, next:string){
    this.localResult = localResult;
    this.next = next;
  }
}
interface Component{
  CheckIfCanGoNext: CheckIfGoNextPage;
}
let x:Component = {"CheckIfCanGoNext": CheckIfGoNextPage}

let f = new x["CheckIfCanGoNext"]("sss", "")
console.log(f.localResult);

If I set CheckIfCanGoNext to any it will work but I will lose the type.

Answer №1

If you ever need to determine the type of a specific named value, you can utilize the typeof type query operator. To assign the actual value named CheckIfGonextPage, which is the class constructor, to the CheckifCanGoNext property of a Comp object, you can reference that type as typeof CheckIfGonextPage:

interface Comp {
    CheckifCanGoNext: typeof CheckIfGonextPage;
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }
let f = new x["CheckifCanGoNext"]("sss", "")

Another approach would be using a construct signature to describe something that can be constructed with the new operator. It resembles a function call signature, but with the addition of the word new before it:

interface Comp {
    CheckifCanGoNext: new (localResult: string, next: string) => CheckIfGonextPage
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }

let f = new x["CheckifCanGoNext"]("sss", "");

Both methods should achieve the desired outcome.

Link to Playground for code demonstration

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

Manually close the AntD Menu without using any shortcuts

I'm facing a unique situation with my table implemented using antd. Each row has a dropdown menu that opens a modal upon clicking. To ensure the dropdown menu doesn't trigger the row click event, I used stopPropagation on the menu item click. Eve ...

What are the best practices for integrating PrimeVue with CustomElements?

Recently, I decided to incorporate PrimeVue and PrimeFlex into my Vue 3 custom Element. To achieve this, I created a Component using the .ce.vue extension for the sfc mode and utilized defineCustomElement along with customElements.define to compile it as a ...

What is the best way to encrypt the JWT decode token payload using Angular 8 on the client-side?

Currently, I am utilizing angular2-jwt to handle the code following an http.get request. In order to properly send an http post request, I must encode the body. let body = { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }; this.http.pos ...

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

Creating an object using a class in Python and extracting data from a list: A step-by-step guide

I've been working with Python on a project involving classes and ElementTree. One of my functions retrieves news from Yahoo's XML, including the title, publication date, and link. I then store this information in a list: import urllib.request im ...

Utilizing a TypeScript getter or local variable to reference a service variable within an Angular component

Suppose you have an array of objects stored in a service export class DataService { private _dataSources : Array<DataSource> contructor(private callerService: CallerService){ this._dataSources = this.callerService.getDataSources(); // fetc ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Encountering issues with setting headers in Angular HttpClient when receiving a response from the server, particularly when testing in Postman

When testing a call in Postman with the single header INFO set to blopp, I expected to receive a JWT token with the value passed in as sub. However, when I removed the header, the token contained an empty sub, which was the anticipated outcome. The script ...

Encountering a compilation error while compiling using Angular Ivy

Encountering a compile time error in my Angular 8 project when enabling angular Ivy. Upgrading to version 8.1.0 did not solve the issue, and I continue to receive the following error: D:\Users\Backup>ng build shared Building Angular Package B ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

Navigating in express

Here is the structure I am working with: server.ts routes/ index.ts homeRoute.ts In server.ts: let app = Express(); app.use(router); In routes/index.ts: const routes = Router(); export default function router() { routes.use('/home' ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

const myList = document.createElement("div"); myList.setAttribute('id', 'name'); const list1 = document.createElement("ul"); const item1 = document.createElement("li"); let value1 = document.createTe ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

The element type 'ReactElement<any>' does not match a JSX element constructor function. 'undefined' cannot be assigned to type 'Element | null'

After attempting the suggested fix of deleting node_modules/ and yarn.lock, then reinstalling everything, I still cannot resolve the issue. I am currently developing a basic router that renders children based on a certain prop: import React, { Fragment } ...

Conceal the message using star symbols

I need help figuring out how to hide a certain type of string input from the user, and then use Angular data binding to display it in another component with part of the data masked with asterisks. I'm not very skilled in JavaScript, so I'm wonder ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

How can I implement dynamic styling for the rows in the PrimeNG table?

I have the MyObject.ts file with the following properties: name: String rowStyle: String In addition, I have a MyComponent.ts file containing: myObject1: MyObject = new MyObject(); myObject2: MyObject = new MyObject(); myObjectList: MyObject[] = []; myO ...

Comparing TypeScript's `return;` with `return undefined;`: which is better?

I encountered a strange behavior that is puzzling to me, and I'm not sure if there's a logical explanation for it. In TypeScript, the following code works perfectly: type UndefinedFunction = () => undefined; let uf: UndefinedFunction = funct ...

TS2322 error: What does it mean when the type is both not assignable and assignable?

I've been delving into the world of generics with Java and C#, but TypeScript is throwing me for a loop. Can someone shed some light on this confusion? constructor FooAdapter(): FooAdapter Type 'FooAdapter' is not assignable to type 'A ...