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

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

How to Extract an Object from an Array using React

I have a situation where I am fetching data from an API using axios. Specifically, on my invoice details page, I am trying to retrieve data for only one invoice using the following code: const id = props.match.params.id; const invoice = useSelecto ...

Discovering if an ID already exists in a Firebase real-time database with React.js

Currently, I am engaged in a React inventory project. In order to avoid duplication when pushing data into the progress.json file, I need to ensure that the data is not already present by checking for the unique id associated with each dataset. Despite m ...

transferring scoped model information to the controller

When using AngularJS, my view is structured like this: <div class="sli1" ng-init="values=[10,20,30,40,50]" <div class="sli2" ng-init="values2=[10,20,30,40,50]" I am attempting to send the initial data models back to the controller for retrieva ...

Can you tell me the name of the Javascript "protocol" or "custom" being referred to here?

From what I can gather, the requests array seems to consist of functions with unique formatting and syntax. However, I'm struggling to find relevant search terms to help me better understand it: var requests = { rewardPoints: function(cb) { io ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

How can I use jQuery to identify the numerical range within class/td/div elements and modify their CSS styles?

1# I need assistance in changing the CSS properties of a TD, Class, and div using a selector that specifies a specific number range. Specifically, I am looking to modify the css of torrent results with a seed count between 250-25000. Any torrents with a se ...

Tips for altering the scrolling rate of a container

I am trying to adjust the scroll speed of specific divs among a group of 5 divs. I came across a solution that changes the scroll speed for the entire document: http://jsfiddle.net/36dp03ur/ However, what I really need is a scenario like this: <div i ...

Issue with the iteration process while utilizing Async.waterfall in a for-loop

This snippet may seem simple, but it represents a real issue in my current code base. When attempting to log the index of a for-loop within an async.waterfall function, I am encountering a peculiar situation where the index value is 2 instead of expected ...

Traverse an array in JavaScript using jQuery, PHP, and AJAX

Trying to iterate through a JavaScript object using AJAX has led me to explore options like json_decode, but it turns out this is an array and not an object. var array = [{type: 'a', value: 1}, {type: 'b', value: 1}] $.ajax{ url: "p ...

Utilizing nested array object values in ReactJS mappings

My JSON API is set up to provide a data structure for a single record, with an array of associations nested within the record. An example of the response from the api looks like this: { "name":"foo", "bars":[ { "name":"bar1" ...

Angular project hosting causing malfunctions in route parameters

Encountering a problem with route parameters after deploying my website on namecheap hosting. Routes Setup: const routes: Routes = [ { path: 'women', component: ProductlistingComponent }, { path: 'women/:search_1', component: ...

Issues with Vue enter transitions not functioning as expected

I am currently involved in a project where I need to implement enter and exit animations for some components. When a component enters the screen, it should come from the bottom, and when it leaves, it should go upwards. The intended functionality is that w ...

Forbidden access error in codeigniter with Ajax request 403

I'm struggling to send a value via Ajax to a Controller file in Codeigniter, but unfortunately I haven't been successful. Despite researching this issue and finding that it has been asked many times before, I still can't seem to find a solut ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

The httpClient post request does not successfully trigger in an angular event when the windows.unload event is activated

Is there a way to send a post request from my client to the server when the user closes the tab or browser window? I have tried using the 'windows.unload'or 'windows.beforeunload' event, but the call doesn't seem to be successful a ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...