What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it.

abstract class genMonster {
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

I have created some monster objects:

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803", 3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079", 1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008", 10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

Here is the method I attempted that isn't working as expected:

class organize extends genMonster{
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number){
    super(id, name, weaknesses, location, challenge, mortality, safety)
  }

  public static getNames(){
    return this.name
  }
}

console.log(organize.getNames());
//logs 'organize'

Any assistance would be greatly appreciated!

Answer №1

When calling the getNames method on the organize function, it returns the constructor name itself as "organize". However, if you want to retrieve the names of the instances (such as Jerry, Patricia, and Lola), you can do so by...

console.log(Jerry.name, Patricia.name, Lola.name);

Answer №2

In order to overcome the limitation of static methods not being able to access instance fields, a solution could be to maintain a list of names used by monsters in a static field named takenNames at the time of each monster's creation.

This can be achieved by implementing a static method called getTakenNames which simply returns the takenNames array.

abstract class genMonster {
  static takenNames: string[] = [];
  static getTakenNames(): string[] {
    return ghost.takenNames;
  }
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {


  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
    ghost.takenNames.push(name);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

console.log(genMonster.getTakenNames())

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

looking to showcase the highest 'levelNumber' of elements within an array

arr1 = [ { "levelNumber": "2", "name": "abc", }, { "levelNumber": "3", "name": "abc" }, { "levelNumber": "3", "name": &quo ...

I'm curious if there is a method to indicate the specific destination within a separate file that the FS module in Node.js writes the data

Whenever I utilize the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});, it successfully writes the data to the JSON file. However, the problem is that the data is not inserted into the array where I actually need ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

Manipulate the CSS of a single div within a group of divs that have the same class using jQuery

I'm attempting to modify the CSS of a specific DIV that shares its class with other divs. I've searched for a solution but haven't had any luck so far. Here is the code I've been using without success: $(".singleOffer").click(functio ...

Resizing a webpage to fit within an IFRAME

Having just started learning HTML, CSS, and JavaScript, I am attempting to incorporate a page as a submenu item on my website. Below is the code that I have so far: <!DOCTYPE html> <html> <meta name="viewport" content="width=1024"> ...

Flow - secure actions to ensure type safety

Currently implementing flow and looking to enhance the type safety of my reducers. I stumbled upon a helpful comment proposing a solution that seems compatible with my existing codebase: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574 I ...

Having Trouble Retrieving Data from Observable in Angular 2 and Typescript

I've encountered a promise error when trying to access a variable that receives data from an observable. Here's an example: Within my component, I have defined the Stat class: export class Stats { name: string; percentage: number; constru ...

What is the best way to display tip boxes for content that is added dynamically?

One of the challenges with my web page is that dynamically added content does not display tipboxes, unlike items present since the page load. I utilize the tipbox tool available at http://code.google.com/p/jquery-tipbox/downloads/list. To illustrate the i ...

Implementing an inline cache for <script> tags that load AJAX content

Looking for a way to cache <script src> received through AJAX requests? Currently, each call attempts to load the src via AJAX by default. However, the issue is that this script remains constant throughout the session and only needs to be re-evaluate ...

Leverage the power of Next.js Dynamic routing query object with an SWR fetch request

While working with Next.js dynamic routing, I am facing an issue where my SWR fetch request is being called before the query object is properly set. This occurs specifically when using the routing query object. Let's take the example of a dynamic rou ...

What is the best way to divide multiple event handlers in jQuery?

Is there a way to organize the code below more effectively by splitting the multiple events into separate lines? $document.find('body').on( 'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

If the option of "none" is chosen, I would like to deactivate all checkbox selections

Struggling with disabling all checkboxes in a PHP form when the NONE option is selected. <h5>HEALTH OF STUDENT</h5> <p>Any physical, emotional, or other difficulties to be aware of?</p> <table> <td>Hearing ...

Executing Javascript without invoking the default behavior

Recently, I've been delving into the world of JavaScript and experimenting with the prevent default command for ajax pagination. Here's the code I've come up with: http://jsfiddle.net/6pqfH/2/ $('.pagination').click(function(e){ ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

"Error 404: Invalid request encountered while using React and

I am encountering an issue with a 404 not found error when I attempt to send a post request in React. My code involves using Django Rest Framework on the backend and React Axios on the frontend, but I am facing errors while making the post request. Below i ...

What is the best way to eliminate a blank array in JavaScript?

After countless hours of searching, I am reaching out for help with an issue that has me stumped. My Node.js application relies on JSON files for project configurations. Using the 'fs' module, I read the JSON file, parse it into a JavaScript obje ...

What is the best way to assign a TypeScript type as the object type within an array of objects sourced from a different interface?

I am working with a generated interface that looks like this: export interface StaticPageLeftMenuV1 { id: string status: 'draft' | 'published' environments: ('dev' | 'staging' | 'production')[] ...

Attempting to generate printed documents with multiple components spread across individual pages using react-to-print

I am working with the react-to-print library and I have a requirement to print a list of components, with each component on its own separate page. However, when I click on the print button, I encounter an error stating that the argument does not appear to ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...