Specify the second parameter as a generic class that corresponds to the first parameter of the function

Given the example below, the second parameter of the fn function requires a class with a static attribute controle and an instance attribute controle, both of type number.

interface Base {
    controle: number
    new(...args: any[]): {
        controle: number
    }
}

function fn(constructor: Base) {
    return [constructor];
}

fn(class {
    static controle = 100;
    controle = 100;
});

fn(class {
    static controle = ""; // <--- throw type error
    controle = "";        // <--- throw type
});

playground example


Considering the example below, the second parameter of the fn function has the type Base<T> where T is a key of DocumentEventMap. For instance, if T is "click", then the second parameter of the fn function must be a class with a static attribute type and an instance attribute type, both of type "click".

type EventType = keyof DocumentEventMap;

interface Base <T extends EventType>{
    type: T
    new(...args: any[]): {
        type: T
    }
}

function fn(constructor: Base<"click">) {
    return [constructor];
}

fn(class {
    static type: "click" = "click";
    type: "click" = "click";
});

fn(class {
    static type: "abort" = "abort"; // <--- throw type error
    type: "abort" = "abort";        // <--- throw type error 
});

playground example


Here's my question: In the second example, I hard-coded "click" as the generic type. How can I make it a dynamic value? Please consider my attempt below:

type EventType = keyof DocumentEventMap;

interface Base <T extends EventType>{
    type: T
    new(...args: any[]): {
        type: T
    }
}

function fn<K extends EventType>(type: K, constructor: Base<K>) {
    return [type, constructor];
}

fn("click", class {
    static type: "click" = "click";
    type: "click" = "click";
});

fn("click", class {
    static type: "abort" = "abort"; // <--- should throw type error, but it doesn't
    type: "abort" = "abort";        // <--- should throw type error, but it doesn't
});

playground example

Therefore, how can I correctly define the second parameter as a generic class based on the first parameter of a function?


I'm Brazilian, and my English may not be perfect, so feel free to correct my text if necessary.

Thank you

Answer №1

After much deliberation, I have uncovered a solution to this perplexing conundrum. Please refer to the resolution provided below:

type EventType = keyof DocumentEventMap;

interface Base<T extends EventType> {
    type: T
    new(...args: any[]): {
        type: T
    }
}

function fn<K extends EventType, U extends Base<K>>(type: K, constructor: U) {
    return [type, constructor];
}

fn("click", class {
    static type: "click" = "click";
    type: "click" = "click";
});

fn("click", class {
    static type: "abort" = "abort"; // <--- throw type error
    type: "abort" = "abort";        // <--- throw type error
});

playground example


To crack the code on this issue, I introduced an additional generic type that is interdependent on the initial generic type

K extends EventType, U extends Base<K>
.

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

Ionic 2: Issue with Custom Provider Resulting in "Unable to Resolve All Parameters"

I have created a test provider and I am attempting to inject it into two pages for the purpose of sharing data and methods. However, when I add the provider to the page constructor, an error is thrown, stating "Can't resolve all parameters for Charact ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

Typescript: Streamline the process of assigning types to enum-like objects

One common practice in JavaScript is using objects as pseudo-enums: const application = { ELECTRIC: {propA: true, propB: 11, propC: "eee"}, HYDRAULIC: {propA: false, propB: 59, propC: "hhh"}, PNEUMATIC: {propA: true, propB: ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

Using Angular 8 for Filtering Firebase Data

I need to implement a filter on the titles of my stored data, but I am facing an issue where the structure of the filtered data changes. The original "key" of the data gets deleted by the filter and is replaced with an index instead. Link to repository : ...

Passing a callback to a third-party library resulted in an unexpected error

My React+TypeScript code utilizes a component from a third-party library. <ThirdPartyComponent onSelect={(value: any) => {...}} /> The eslint-typescript tool is flagging this as an error: Unexpected any. Specify a different type. eslint(@type ...

Step-by-step guide on deploying Angular Universal

Exploring Angular universal and working on understanding deployment strategies. Check out the Github repository at https://github.com/angular/universal-starter This project includes Angular 2 Universal, TypeScript 2, and Webpack 2. After running the comm ...

Setting a maximum limit for selections in MUI Autocomplete

Code updated to display the complete script logic. I want to restrict the number of selections based on a value retrieved from the database, but in this example, I have set it to 3 manually. The error message I'm encountering is "Cannot read properti ...

What is the best way to fetch the id of the option that has been chosen from a bootstrap drop-down menu?

I recently created a basic drop-down list like this: https://i.sstatic.net/4Tlxx.png Here is the HTML code for it: <select class="form-control" id='0' (change)="retrieveValue($event.target)"> <option id='0'>{{ g ...

Can TypeScript identify and eliminate any undefined values within an array effectively?

Is there a simple and efficient method to achieve the following: const x: (string|undefined)[] = ['aaa', undefined, 'ccc']; const y = _.filter(x, it => !!it); in order for TypeScript to correctly identify y as string[], without nee ...

What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this: CREATE TABLE IF NOT EXISTS users ( "id" SERIAL PRIMARY KEY, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "name&quo ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Broaden the scope of a `Record<string, string[]>` by adding a new type of property

When working in Typescript, it appears that defining the type as shown below should create the desired outcome: interface RecordX extends Record<string, string[]> { id: string } However, an error is thrown stating: Property 'id' of t ...

Using Higher Order Components (HOC) in combination with Redux compose and Typescript

I am trying to leverage two Higher Order Components (HOC) with Redux compose, but the compiler is not generating the correct types. The Compose function is defined in the Redux source code here source code. To better understand how the code works, you ca ...

react-i18next - The function call does not match any overload when the specified type is `string`

I am currently utilizing react-i18next in conjunction with React and TypeScript. Interestingly, when I attempt to load a property using a string literal and type inference, everything works seamlessly. However, once I specify the type as string, an error i ...