Retrieve a static property from a specific type

I've encountered a dilemma with the code snippet below:

class Action {
    public static DEPENDENCIES: (typeof Action)[] = [];

    public static MIN_USES: number | null = null;
    public static MAX_USES: number | null = null;
}

class SomeAction extends Action {
    public static DEPENDENCIES = [SomeOtherAction];

    public statuc MIN_USES = null;
    public static MAX_USES = 1;
}

class SomeOtherAction extends Action {
    public static DEPENDENCIES = [];

    public static MIN_USES = 1;
    public static MAX_USES = 1;
}

When trying to access a static property like this:

class Turn {
    public can(A: typeof Action) {
        console.log(A.MIN_USES);
    }
}

turn.can(SomeOtherAction); // console.log(1);

Now, I aim to give SomeOtherAction a constructor with two parameters.

This modification triggers an error message:

Class static side 'typeof SomeOtherAction' incorrectly extends base class static side 'typeof Action'.

The root of the issue lies in the differing constructor signatures, which led me to replace (typeof Action)[] with

(new(...args: any[]) => Action)[]
.

Nevertheless, by making this change, it seems that I lose the ability to access static properties:

Property 'MIN_USES' does not exist on type 'new (...args: any[]) => Action'.

Is there a way to reconcile accessing static properties and accommodating various constructor signatures?

Answer №1

Your issue stemmed from using the typeof operator, which enforces that class structures are identical, including the new property (constructor).

I resolved this problem with the following code:

type ActionType = (Omit<typeof Action, 'new'>)

class Action {
    public static DEPENDENCIES: ActionType[] = [];
    
    public static MIN_USES: number | null = null;
    public static MAX_USES: number | null = null;
}

class SomeOtherAction extends Action {
    public static DEPENDENCIES = [];

    public static MIN_USES = 1;
    public static MAX_USES = 1;

    constructor(arg1: string, arg2: number) {
        super()   
    }
}

class SomeAction extends Action {
    public static DEPENDENCIES = [SomeOtherAction];

    public static MIN_USES = null;
    public static MAX_USES = 1;
}

class Turn {
    public can(a: ActionType) {
        console.log(a.MIN_USES);
    }
}

const turn = new Turn()
turn.can(SomeOtherAction); // console.log(1);

The ActionType now represents the structure of Action without the constructor, resolving the constraint issue.

By creating and implementing this type, all occurrences of typeof Action have been replaced with ActionType.

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

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Determining the name of the currently focused DOM element in Angular2

How can I detect the name of a selected element from a group of select elements on a page? For example: <select (click)="functionDetectName()" name="test1"> <select (click)="functionDetectName()" name="test2"> <select (click)="functionDete ...

Authorizer custom is not being triggered for websocket connection event

I'm currently working on implementing a custom authorizer for an API Gateway Websocket API. Below is my custom authorizer implementation using CDK: const authFunc = new lambda.Function(scope, utils.prefixed("WebsocketAuth"), { runtime: ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

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 ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Utilizing object as props in ReactJS with TypeScript

I'm new to working with ReactJS, and I made the decision to use typescript for my current project. The project is an application that fetches movies from an API and displays them. Take a look at the app: import React from 'react'; import &a ...

Include a parameter in a type alias

Utilizing a function from a library with the following type: type QueryFetcher = (query: string, variables?: Record<string, any>) => Promise<QueryResponse> | QueryResponse; I aim to introduce an additional argument to this type without mod ...

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 ...

Matching the appropriate data type for interface attributes

In the process of developing a module (module1), I have defined the following interface type: interface ModuleOneInterface { keyOne: customInterface; keyTwo: customInterface; keyThree: customInterface; } Now, as I work on another module (modul ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

Determine the class of an object within the "keyof" parameter by utilizing both property and generic types

I have a requirement to create an interface with generic types that can accept an object with keys representing "root field names" and values as arrays of objects defining sub-fields with the key as the name of the sub-field and the type as the value' ...

Validation with React Hooks does not function properly when used on a controlled component

I've recently started using react hook form and I've created a custom component based on material ui's autocomplete. The issue I'm facing is that react hook form isn't validating the field at all. Let me show you how the setup look ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

In Typescript, convert an object into a different type while maintaining its keys in the resulting type

Imagine you have a code snippet like this type ResourceDecorator = (input: UserResourceDefinition) => DecoratedResourceDefinition const decorate: ResourceDecorator = ... const resources = decorate({ Book1: { resourceName: 'my-book', ...

The specified '<<custom component name>>' argument does not match the 'Type<<custom component name>>' parameter

I'm currently facing an error that indicates a type parameters mismatch, but I can't pinpoint where in the process it's happening. Argument of type 'ModalUserInfoComponent' is not assignable to parameter of type 'Type<Mo ...

What are the benefits of utilizing TypeScript declarations? How can you demonstrate their value with concrete examples?

I'm a bit confused about the use of declaration in TypeScript. It seems like the compiler doesn't compile it into the js file, so what is the purpose and advantage of using declaration? Can someone please explain this to me? ...

Unselecting a line will result in the disabling of all chart lines

Currently, I am working with Primeng and incorporating multiple charts into my view. One feature of Primeng that I have successfully implemented is disabling lines. I am following this particular example: Primeng provides a handy function on their site: ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Angular 2 Demonstrate Concealing and Revealing an Element

I am currently facing an issue with toggling the visibility of an element based on a boolean variable in Angular 2. Below is the code snippet for showing and hiding the div: <div *ngIf="edited==true" class="alert alert-success alert-dismissible fade i ...