What is the best way to access static variables from the class(es) of an object in TypeScript?

I am seeking a way to access the static members of classes, including parent classes from which an object was created. Currently, I am adding each class to an array in the constructor as a workaround. However, with thousands of classes to define, I am hoping for a more elegant solution or a method to restrict the Type to the master class.

Below is some sample code illustrating my point:

type Class = { new(...args: any[]): any; }

class Animal {
    static description = "A natural being that is not a person";
    classes: Class[] = [];
    
    constructor() {
        this.classes.push(Animal)
    }
}

class Mammal extends Animal {
    static description = "has live births and milk";
    
    constructor() {
        super(); // adds Animal to classes
        this.classes.push(Mammal)
    }
}

class Dog extends Mammal {
    static description = "A man's best friend";
    
    constructor() {
        super(); //adds Animal and Mammal to classes
        this.classes.push(Dog)
    }
}

class Cat extends Mammal {
    static description = "A furry purry companion";
    
    constructor() {
        super(); //adds Animal and Mammal to classes
        this.classes.push(Cat)
    }
}

let fido = new Dog()
fido.classes.forEach(function(i) {
    console.log(i.description)
}

I would like classes to only accept instances of Animal and its extensions.

Answer №1

If you want to traverse the prototype chain of an object instance, you can do so as follows:

function describe(animal: Animal) {
    for (let prototype = Object.getPrototypeOf(animal); prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype))
        console.log(prototype.constructor.description);        
}

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

How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI. This is my Service: fetchPdfDocument(): Observable<any> { return this.httpClient .get(this.configuration.serverUrl + this.configuration.getPdfDoc, { re ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

Versatile functions and unique index classifications

I need help creating a versatile function that takes a type argument "T" representing an object. It should use keyof T to determine the first argument named "property". However, I am struggling with defining the type of the second argument, called "value", ...

How to share data between two different components in Angular 6

I have a component called course-detail that fetches data (referred to as course) from my backend application. I want to pass this data to another component named course-play, which is not directly related to the course-detail component. The goal is to dis ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...

Tips for importing a .ts file into another .ts file within an Angular 5 application

I have a bunch of utility methods stored in a file called utils.ts that I want to reuse across multiple components. I'm not sure if it's even possible, and if it is, where should I place the import statement and what would be the correct syntax. ...

reading an array of objects using typescript

Trying to retrieve an object from an array called pVal. pVal is the array that includes objects. I am attempting to obtain the value of "group" based on the id provided. For instance, if the id is equal to 1, it should display "VKC". Any assistance woul ...

What is the best way to design a basic server component that has the ability to retrieve data in NextJS 13?

Exploring the world of NextJS, I am currently utilizing NextJS 13 with the new app directory instead of the traditional pages directory structure. Despite trying various methods to fetch data, none seem to be working as expected. The process should be stra ...

The value of "x" cannot be altered, yet it remains unrestricted

In my Angular 10 project with Typescript 3.9, I have the following class definition: export class Document { constructor( public id: number, ... public tags: Tag[] ) { this.id = id; ... this.tags = ta ...

The Updating Issue: Angular 2 Table Fails to Reflect Value Changes

I have initialized a table with user details using the ngOnInit() method. When I click on the "create user" button, it opens a form to add a new user to the database. However, the table does not update automatically with the new user's information. H ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

Choose a row by selecting the checkbox in the Kendo UI grid using TypeScript

I'm just starting out with Kendo UI and Angular 2, and I'm currently working on integrating Kendo UI with Angular 2. Specifically, I have a Grid Module set up with checkboxes in each row. My goal is to extract the row ID or any other field value ...

"ENUM value is stored in the event target value's handle property

My issue lies with the event.target.value that returns a 'String' value, and I want it to be recognized as an ENUM type. Here is my current code: export enum Permissions { OnlyMe, Everyone, SelectedPerson } ... <FormControl> & ...

Passing a variable from one Tkinter class to another Tkinter class within the same window - not involving a toplevel frame

How can I pass the value of a variable from one class to another in tkinter with python, especially when they are sharing the same frame instead of being separate windows? For instance, if I have a login window and want to send the username and account pr ...

Angular2 Release Candidate 5: Unable to connect to 'Property X' because it is not recognized as a valid property of 'Child Component'

I am currently working on upgrading a small Angular2 project, which is based on the Angular2 Seed project, to Angular2 RC5. Within my project, I have various features, one of them being referred to as home. The Home component utilizes a child component na ...

Tips for inserting a string into an array nested within an object stored in a state array

Currently, the variable sizeVariant is a string array and I am trying to append strings to it using an onClick event. The function findIndex seems to be working fine. However, there seems to be an issue with the concatenation section. It appears that using ...

The autoimport feature is not supported by the Types Library

My latest project involves a unique library with only one export, an interface named IBasic. After publishing this library on npm and installing it in another project, I encountered an issue. When attempting to import IBasic using the auto-import feature ( ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

Office-Js Authentication for Outlook Add-ins

I am currently developing a React-powered Outlook Add-in. I kickstarted my project using the YeomanGenerator. While working on setting up authentication with the help of Office-Js-Helpers, I faced some challenges. Although I successfully created the authen ...