Using Class as a Parameter

I recently started using TypeScript and encountered an implementation issue. I'm working on a class that takes another class as an argument. The challenge is that it can be any class, but I want to define certain possible class properties or methods. Let's assume this class may have a singleton static property. I attempted to utilize a Class generic:

type Class<T> = new (...args: any[]) => T;

class ClassResource {
  private _resource;
  private _singleton;
  
  constructor(resource: Class<any>) {
    this._resource = resource;
    this._singleton = resource.singleton;
  }

  // some methods

  getClassInstance() {
    return new this._resource();
  }
}

However, I encountered the following error:

Property 'singleton' does not exist on type 'Class'

How can I properly define this "abstract" class and specify only specific potential properties without restricting them?

Answer №1

If you want your type to require the class to have a singleton property, simply include that in your definition.


type _Class<T>= new (...args: any[]) => T;

type ClassType<T> =  _Class<T> & {
    singleton: T
}

class ClassResource {
  private _resource;
  private _singleton;
  
  constructor(resource: ClassType<any>) {
    this._resource = resource;
    this._singleton = resource.singleton;
  }

  // some methods

  getClassInstance() {
    return new this._resource();
  }
}


class A {
    
    static singleton = new A();

    getHello() {
        return ''
    }
}

new ClassResource(A); //works

class B  {
    getHello() {
        return ''
    }
}

new ClassResource(B); // doesn't work

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

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

What is the best way to retrieve the dataset object from a chart object using chart.js in typescript?

Currently, I am facing a challenge in creating a new custom plugin for chart.js. Specifically, I am encountering a type error while attempting to retrieve the dataset option from the chart object. Below is the code snippet of the plugin: const gaugeNeedle ...

The [image link] in the NextJS image was loaded in advance using link preload, but it was not utilized within a short time after the window finished loading

While working on my blog website with NextJS, I encountered a warning in the console related to using next/image: The resource http://localhost:3000/_next/image... was preloaded using link preload but not used within a few seconds from the window's lo ...

Retrieve type definitions for function parameters from an immutable array containing multiple arrays

My current challenge involves implementing a function similar to Jest's test.each iterator: // with "as const" forEach([ [ 1, 2, 3 ], [ "a", "b", "c" ], ] as const, (first, second, third) => { // ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

What are the steps to correct a missing property in an established type?

Currently, I am in the process of converting an existing Node.js + express application from plain JS to TypeScript. Although I understand why I am encountering this error, I am unsure about the correct approach to resolve it. The type "Request" is coming f ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

What is the best way to access all the attributes (excluding methods) of an object in a class instance?

My goal is to generate a new object type that inherits all the properties from an existing class instance. In other words, I am looking for a way to transform a class instance into a plain object. For example, consider the following scenario: ...

The image is malfunctioning in the production environment, but functions perfectly on the localhost server

Currently, I am in the process of creating a website utilizing Next.js and Mantine. In order to incorporate my logo into the Header section, I utilized the Image component from next/image. Unfortunately, upon deployment, the image does not display as inten ...

What is the best way to convert the NextJS router.query.id to a string?

As a newcomer to TypeScript and the T3 stack (React Query / Tanstack Query), I am facing an issue with typing companyId as string. I want to avoid having to type companyId as string every time I use it in my code, but I'm struggling to find the best p ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

ts-node: The colon symbol was not expected in this context

As I work on developing a backend server for my application, I made the decision to switch from using babel-node as the executor to utilizing ts-node. The command defined in my package.json file is: "server": "cd server && ts-node --project tsconf ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Generate a div element dynamically upon the click of a button that is also generated dynamically

Putting in the effort to improve my Angular skills. I've found Stack Overflow to be extremely helpful in putting together my first app. The service used by my app is located in collectable.service.ts: export class CollectableService { private col ...

What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database. HTML: <tr *ngFor="let profile of profiles | async"> <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model=&apo ...

Disabling the use of console.log() in a live environment

In an effort to disable console logs for production environments in my angular application, I implemented the code below. While it successfully suppresses logs in Chrome, IE 11 continues to display them. Here is the snippet from main.ts: if (environment. ...

Firebase data causing issues with ion-gesture recognition?

Hey there! I'm currently facing an issue with my ionic app. I added the ion-gesture to my project, but due to the ngFor loop pulling data from Firebase, the cards are unable to move. Here's a snippet of my code: <ion-card *ngFor="let po ...

Developing a typescript React component with a generic callback event handler function passed as a prop

I'm struggling with developing a callback event handler function that can be passed down as a prop to my component. My objective: Allow users to provide a custom callback function that: always accepts the same argument an event (not a react/dom even ...