create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Plants of that type.

At the moment, I only have one Plant called Sunflower, and now I want to instantiate the Sunflowerplant in the build method within the Cell class.

However, when attempting this approach, I encountered the error:

Cannot create an instance of an abstract class.
This issue makes sense to me. Is there a way to ensure that only non-abstract classes which extend from Plant can be passed as a Parameter for the build() method, or do I need to implement some kind of if (!c isAbstract) check?

abstract class Plant {
  public static dmg: number;
  public static cost: number;

  constructor(cell: Cell) {
    this.cell = cell;
  }

  cell: Cell;
}

// More Plant types could be created like this
class Sunflower extends Plant {
  public static dmg = 0;
  public static cost = 50;
  cell: Cell;

  constructor(cell: Cell) {
    super(cell);
  }
}

class Cell {
  build(c: typeof Plant) {
    if (c.cost <= game.money) {
      this.plant = new c(this); //Cannot create an instance of an abstract class.
      game.money -= c.cost;
    }
  }
}

// Example of building plants
let c = new Cell();
c.build(Sunflower);

Answer №1

You have the ability to achieve it in this way:

class Cell {
    
  generate<T extends Plant>(plant: (new (cell:Cell) => T)) {
    const plantInstance = new plant(this); 
  }
}

Access Playground Demo

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

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

Ensure that the output of a function in Typescript matches the specified data type

Looking for a way to inform TypeScript that the output of a function will always meet the type requirements of a variable, therefore avoiding any error messages? Type 'string | Date' is not assignable to type? For example: const getStringOrDat ...

Utilizing Angular2 with Firebase for efficient denormalized data queries

I am currently working on crafting a query for a denormalized database. Drawing inspiration from the example showcased in Firebase's blog post, my objective is to: Retrieve the array of forms associated with the current user and return references to ...

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

Error: The activation of the extension in vscode failed because the module cannot be found using non-relative import

Currently, I am in the process of developing a Visual Studio Code extension. In this project, I have opted to utilize non-relative imports in TypeScript. For instance: import ModuleA from 'modules/ModuleA'; The actual location of the folder for ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

Exploring the power of combining React, styled-components, and TypeScript: Creating a functional component that encapsulates a styled component

Struggling to create a wrapper for my styled component with proper types. Imagine having a styled component defined like this: const Button = styled.button<ButtonProps>` background-color: ${(props) => props.color}; `; Now the goal is to have a ...

Analyzing different kinds of inputs received by a function

Let's say we have the following abstractions for fetching data from an API: Data storage class class DataItem<T> { data?: T | null } Query function function queryData ( fn: () => Promise<any> item: DataItem<any> ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Enhancing the selection of options in Angular 2 using object values

When I retrieve a list of object values from an API, each object contains a property to identify the selected item. I am successfully binding the items list to the view. Here is the JSON data: https://i.sstatic.net/itmfh.png Below is my code snippet: & ...

There is an issue with the Angular Delete request functionality, however, Postman appears to be

HttpService delete<T>(url: string): Observable<T> { return this.httpClient.delete<T>(`${url}`); } SettingsService deleteTeamMember(companyId: number, userId: number): Observable<void> { return this.httpService.delete< ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

Using vue-router within a pinia store: a step-by-step guide

I'm currently setting up an authentication store using Firebase, and I want to direct users to the login/logged page based on their authentication status. My goal is similar to this implementation: https://github.com/dannyconnell/vue-composition-api- ...

Angular Navigation alters the view

I want to navigate to a different page using Angular routing, but for some reason it's not working. Instead of moving to the designated Payment Component page, the content is staying on my Main Component. Why is this happening? app.routing.module.ts ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: https://i.sstatic.net/RoGER.png The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should ...

Angular/NestJS user roles and authentication through JWT tokens

I am encountering difficulties in retrieving the user's role from the JWT token. It seems to be functioning properly for the ID but not for the role. Here is my guard: if (this.jwtService.isTokenExpired() || !this.authService.isAuthenticated()) { ...

Creating a Mocha+Chai test that anticipates an exception being thrown by setTimeout

Here is what I have: it('invalid use', () => { Matcher(1).case(1, () => {}); }); I am trying to ensure that the case method throws an exception after a delay. How can I specify this for Mocha/Chai so that the test passes only if an exce ...