What methods can I use to access the animalType in a generic type?

Can you guide me on how to access the value of the generic, static variable animalType in T.animalType from the given example code below?

export class main {

    constructor() {

        var myWorker: worker = new worker();
        myWorker.whatAmI();

    }

}

export class worker extends workerBase<dog> {

}

export class workerBase<T extends animal>
{
    public whatAmI() {
        //output animal type as "dog"
        console.warn("Animal type: " + T.animalType); // <<-- this will NOT work, but this is what I want to achieve
    }
}

export class animal {
    public static animalType: string = "any";
}

export class dog extends animal {
    public static animalType: string = "dog";
}

Answer №1

Runtime in Javascript does not support generic types as it lacks a concept of types.

Illustration:

class A<T> {
    private x: number;

    constructor(x: number) {
        this.x = x;
    }
}

This Compiles to:

var A = (function () {
    function A(x) {
        this.x = x;
    }
    return A;
}());

In the compiled JS above, the type of x (number) and T are not preserved.

A workaround is:

abstract class Animal {
    abstract getType(): string;
}

class Dog extends Animal {
    getType(): string {
        return "dog"; 
    }
}

class MyClass<T extends Animal> {
    private pet: T;

    constructor(pet: T) {
        this.pet = pet;
        console.log(`pet type: ${ this.pet.getType() }`)
    }
}

let dog = new Dog();
let myPet = new MyClass(dog); // pet type: dog

(code in 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

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

Using Redux and Typescript to manage user authentication states can help streamline the process of checking whether a user is logged in or out without the need for repetitive checks in the mapStateToProps function

In the process of developing a web application utilizing React & Redux, I am faced with defining two primary "states" - Logged In and Logged Out. To tackle this challenge, I have structured my approach incorporating a union type State = LoggedIn | LoggedO ...

Confirm the presence of a particular sub collection within Firebase/Firestore by returning true

Can you confirm if the sub-collection named 'categories' exists within the users collection in Firestore? Please return true if it exists and false if it does not. ...

Utilize an array of JSON objects to populate an array of interfaces in Angular/Typescript

I am currently facing a dilemma - my code is functioning without any errors when executed, but my text editor is flagging an issue stating that the property 'categories' does not exist on type 'CategoryInterface[]' (specifically on the ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

What is the procedure to prevent Angular CLI from including a specific typings file in my project configuration?

I've integrated JointJs into my Angular CLI project, but I'm encountering typing errors during the build process: https://i.sstatic.net/3ihS3.png The error messages point to the file node_modules/jointjs/types/joinjs.d.ts, which is not the corr ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

Typescript: Assigning Variables Without Prior Declaration

In my upcoming Node.js application, I decided to use TypeScript for development. However, I encountered a perplexing issue while working on the code below: class AuthService { public async init(req: Request, res: Response) { let user: IUser | ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Visual Studio - Error TS1005 'Unexpected token'

After spending nearly 5 hours scouring the internet for a solution, I am still unable to resolve this persistent issue. The responses I've found so far do not seem to address the specific problem I'm facing. Although I have upgraded the tsc vers ...

Angular project icons not displaying in the browser

My current project in Angular was functioning properly until recently. I am facing an issue where the images are not being displayed on the browser when I run ng serve, resulting in a 404 error. Interestingly, everything else seems to be working fine witho ...

Ways to restrict users from inputting alphabets in TextField using material ui

I've set up a TextField where users can only input positive digits. Currently, I'm using the following onKeyDown event: <TextField label={distanceError} error={!!distanceError} defaultValue={kpoints.distance} on ...

Implement conditional props for a React component by linking them to existing props

In my current project, I am working on a component that has a loading state. The component has an isLoading prop which determines whether the component is currently in a loading state or not: interface CustomImageComponentProps { isLoading: boolean ...

Angular's OnChanges event is triggering for an Input variable, however the variable remains unchanged

I've encountered a new issue that I'm hoping someone can help me with. I'm working on a simple parent-child component relationship where an Input variable is passed into a ChildComponent. The ChildComponent in question is a bootstrap modal, ...

Unable to tune in and capture a tauri worldwide event happening concurrently in two separate vue files

I want to develop a small program that includes the following features: The initial Vue component named "Start.vue" should open a new window upon clicking a button The new window should consist of another component called "Playboard.vue" "Start.vue" shoul ...

Creating an Ionic 3 canvas using a provider

I recently followed a tutorial on integrating the canvas API into Ionic, which can be found at this link. However, I encountered an issue where all the canvas-related functions had to be placed within the pages class, making it quite cumbersome as these f ...

A reference to 'this' is not permissible within a static function in Types

Based on this GitHub issue, it is stated that referencing this in a static context is allowed. However, when using a class structure like the following: class ZController { static async b(req: RequestType, res: Response) { await this.a(req) ...

Troubleshooting Node TypeScript with Visual Studio Code using webpack bundling

(In a similar context to this query, but more focused on VsCode) I am attempting to debug the AngularU starter kit with Visual Studio Code. However, it is combining the TypeScript output into one bundle.js along with a side bundle.js.map: ↳web ↳dis ...

Is it possible that VS Code can't recognize 'ngbNavItem' as a valid property of 'li'?

The current situation: Our Angular app is in production and utilizes various libraries such as ng-select, angular-fontawesome, ng2-charts, ngx-quill, ng-bootstrap, and others. Everything seems normal with these libraries except for ng-bootstrap, which alo ...