Leveraging Class Types with Generics

Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics

To make it work, I just need to call a static method before instantiation. Let's adjust the example like this:

class BeeKeeper {
    hasMask: boolean = true;
}

class ZooKeeper {
    nametag: string = "Mikle";
}

class Animal {
    static beforeInit() {
        console.log('do something here');
    };

    numLegs: number = 4;
}

class Bee extends Animal {
    static beforeInstantiate() {
        console.log('do some bee stuff here');
    };
    keeper: BeeKeeper = new BeeKeeper();
}

class Lion extends Animal {
    static beforeInstantiate() {
        console.log('do some lion stuff here');
    };
    keeper: ZooKeeper = new ZooKeeper();
}

function createInstance<A extends Animal>(c: new () => A): A {
    c.beforeInstantiate(); // TS2339: Property 'beforeInit' does not exist on type 'new () => A'.
    return new c();
}

createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;

I added a static method to the Animal class and called it in the createInstance function just before instantiation. However, an error occurred:

 TS2339: Property 'beforeInit' does not exist on type 'new () => A'.

How can I modify the type of c to let TypeScript recognize the static functions?

Answer №1

If you want to specify the type for c more precisely, you can do it like this:

c: (new () => A) & { beforeInstantiate: () => void }

Or alternatively:

c: { new (): A, beforeInstantiate: () => void }

Both of these types indicate that c must be a constructor of class A, and it must also have a static property named beforeInstantiate.

Check out the Playground link here

Just a heads up, your example uses beforeInit in Animal, but beforeInstantiate in the others. It may be a good idea to keep those consistent.

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

Why is the getElement().getProperty("value") function not functioning properly?

I am facing an issue with reading a property in my web component. I am puzzled as to why it is not working correctly. I created a simple example, and after clicking the button, I expect to retrieve the value of the property, but it returns null. I am unsur ...

What is the process of converting the new syntax of SomeFunction() to TypeScript?

When I try to convert a basic JS file to TS while having implicit "any" disabled, I encounter the following error: Error TS7009: When attempting to create a new expression without a constructor signature, it implicitly defaults to an 'any' typ ...

Ways to use DecimalPipe for rounding numbers in Angular - Up or down, your choice!

Looking to round a number up or down using DecimalPipe in Angular? By default, DecimalPipe rounds a number like this: Rounding({{value | number:'1.0-2'}}) 1.234 => 1.23 1.235 => 1.24 But what if you want to specifically round up or do ...

What is the best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

Interfaces in Typescript

In my Angular 2 project, I am working on creating an interface for a complex object. Here is the code snippet of the object: // Defining the render state object this.aRenderState = { model: "", colour: false, showWireframe: false, showGrid: true, ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...

Finding the number of elements in a FirebaseListObservable involves accessing the `length` property

One of the tasks in my Angular 2 application involves retrieving data from a Firebase database and storing it in a FirebaseListObservable. I have a method called getStatus that is supposed to determine the number of elements in this FirebaseListObservable. ...

The Next.js build encountered an error - unable to locate function in next/script module

While constructing a CMS using next.js, one of the key components is media management through Cloudinary. The integration of the Cloudinary Media Library widget was successful during development using next/script. However, an error has now emerged that pre ...

Next.js components do not alter the attributes of the div element

I am encountering a problem with nextjs/reactjs. I have two tsx files: index.tsx and customAlert.tsx. The issue that I am facing is that the alert does not change color even though the CSS classes are being added to the alert HTML element. Tailwind is my c ...

Utilizing TypeScript for enhanced Chrome notifications

I am currently developing a Chrome app using TypeScript (Angular2) and I want to implement push notifications. Here is the code snippet for my notification service: import {Injectable} from 'angular2/core'; @Injectable() export class Notificati ...

The data structure of '(string | undefined)[]' cannot be matched with type '[string | undefined]'

I've been working on a TypeScript project and I've encountered the ts(2322) error as my current challenge. Here's a snippet of my code: import { BASE_URL, AIRTABLE_BASE_ID, AIRTABLE_TABLE_STUDENT, AIRTABLE_TABLE_CLASSES, API_KEY, ...

Distributing utility functions universally throughout the entire React application

Is there a way to create global functions in React that can be imported into one file and shared across all pages? Currently, I have to import helper.tsx into each individual file where I want to use them. For example, the helper.tsx file exports functio ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...

How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data. In my component.ts file: import { HttpClient } from "@angular/common/http"; import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/fo ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

Managing form input in Ionic2 components from external sources in Angular2

Hello there, I am currently facing an issue with managing form validation along with proper styling for nested forms. Here's what I'm aiming to achieve: I have a Page that displays Tabs components with four tabs. Each tab represents a separate @ ...

When running `npm test`, Mocha TS tests encounter failure, but the issue does not arise when executing them

When running tests in my Typescript nodejs project, I use the following command: mocha --compilers ts:ts-node/register,tsx:ts-node/register The tests run successfully with this command. However, when I try to run them using npm test, I encounter the foll ...