Use the class type or any of its derived classes rather than an object of the class itself

I have the following classes

class Foo {}

class A extends Foo {}

class B extends Foo {}

Now, I am looking to create an interface with a property named type that should be of type class rather than an instance of a class.

interface Bar {
    type  : typeof XXXX;     // Unsure about what to fill in here
    value : string;
}

By doing this, I can instantiate the interface as follows

const x: Bar = {
    type  : Foo, // or any of its subclasses like A or B
    value : 'test',
}

I specifically want a reference to the class Foo, and not an instance of it. Therefore, something like this

{
    type : new Foo(),
    value : "test"
}

should not be considered valid.

I hope I have explained my issue clearly.

Answer №1

It appears that your requirement is to create a construct signature in the form of new () => Foo, indicating "a constructor with zero arguments that produces an instance of type Foo". Like so:

interface Bar {
     type: new () => Foo;
     value: string;
}

const x: Bar = {
     type: Foo,
     value: 'test',
};
const y: Bar = {
     type: A,
     value: ""
};
const z: Bar = {
     type: new Foo(), // error!
//   ~~~~ <-- // Type 'Foo' is not assignable to type 'new () => Foo'.
     value: ""
}

Link to Code Playground

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

Issue encountered while declaring a variable as a function in TSX

Being new to TS, I encountered an interesting issue. The first code snippet worked without any errors: interface Props { active: boolean error: any // unknown input: any // unknown onActivate: Function onKeyUp: Function onSelect: Function onU ...

Is it possible to silence the other person's audio using livekit?

As a developer, I create meeting apps using React and livekit technology. I am looking for a reliable method to silence the audio of other participants in the virtual room. Any suggestions? ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

How will the presence of @types/react impact the higher-level files in my project?

https://i.sstatic.net/TfsLf.png https://i.sstatic.net/RqmMS.png Here is the structure of my directories vue node_modules src react_app node_modules @types/react package.json ...other file package.json Why does the presenc ...

Vue cannot detect the component that is provided by my plugin

This unique plugin, currently only includes a single component (coded in TypeScript): import _Vue, { PluginObject } from "Vue"; import MyComponent from "./MyComponent.vue"; const VuePlugin: PluginObject<void> = { install(Vue: typeof _Vue): void { ...

Determine the Angular object's type even if it may be undefined

Currently diving into Angular and looking to create a method that can determine if an object is of type Dog (identified by a woof property). This is the code snippet I have put together so far: export class SomeClass { public animal?: Dog | Cat; ... ...

Create a custom button in Material-UI using Styled-components, and integrate it with React

I'm currently working on a project using React, TypeScript, and styled components along with the material-ui library. I have created styled material-ui buttons as shown below: import React from 'react' import styled from 'styled-compone ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

React Native is throwing an error message saying that the Component cannot be used as a JSX component. It mentions that the Type '{}' is not assignable to type 'ReactNode'

Recently, I initiated a new project and encountered errors while working with various packages such as React Native Reanimated and React Navigation Stack. Below is my package.json configuration: { "name": "foodmatch", "version ...

Working with undefined covariance in TypeScript

Despite enabling strict, strictNullChecks, and strictFunctionTypes in TypeScript, the following code remains error-free. It seems that TypeScript is not catching the issue, even though it appears to be incorrectly typed. abstract class A { // You can p ...

Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking th ...

Guide on importing a markdown file (.md) into a TypeScript project

I've been attempting to import readme files in TypeScript, but I keep encountering the error message "module not found." Here is my TypeScript code: import * as readme from "./README.md"; // I'm receiving an error saying module not found I als ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Is there documentation available for the gcloud output formats, such as the JSON output for each command?

As I work to script the gcloud tool in a TypeScript-aware JavaScript environment known as SLIME, I am utilizing the --format json feature for formatting. The integration is smooth, but I find myself manual analyzing the JSON output of each command to und ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

What is the best way to transfer user data from the backend to the frontend?

I successfully created a replica of YelpCamp using Node and EJS, but now I am attempting to convert it into a Node-React project. Everything was going smoothly until I encountered an issue while trying to list a specific user in the SHOW route. In order to ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation: const MenuList = ():ReactElement => { const router = useRouter(), liElements:any = []; con ...

Is there a way to access a function or variable from within the scope of $(document)?

Whenever I attempt to utilize this.calculatePrice, it does not work and I am unable to access the external variable minTraveller from within the function. numberSpin(min: number, max: number) { $(document).on('click', '.number-spinner b ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...