What is the best way to utilize the parameter of a generic static method within a generic function?

My attempt at utilizing Omit<T, 'id'> within a generic function is shown below:

class Model{
   static create<T extends Model>(a: Omit<T, 'id'>): number{
        return 0;
    }

    id = 0;
    title = 'test';
}

class Child extends Model{
    child = true;
}


function createModel<T extends typeof Model>(model: T, data: Parameters<T['create']>[0]) : InstanceType<T> {
    return {} as InstanceType<T>;
}

const instance = createModel(Child, {title: 'test', child :true }); // trying to include child properties here as the second argument

Playground

When using

Parameters<T.func<InstanceType<T>>>
, I encountered this error:

Cannot access 'T.func' because 'T' is a type, not a namespace. Did you mean to retrieve the type of the property 'func' in 'T' with 'T["func"]'?(2713)

Using

Parameters<T['create']<InstanceType<T>>>
resulted in:

Parameter 'InstanceType' implicitly has an 'any' type.

In addition, there was invalid syntax when createModel had more than 6 parameters

Is there a way to reuse the parameter without introducing a common external type?

Answer №1

Because func is a static method, it does not exist on an instance of Model

I believe this is the solution you are seeking.

function test<T extends typeof Model>(model: T, data: Parameters<T['func']>[0]) : T {
    return {} as T;
}

Edit

Revised response based on the clarifications provided in the question.

class Model {
  static create<T extends Model>(a: Omit<T, "id">): number {
    return 0;
  }

  id = 0;
  title = "test";
}

class Child extends Model {
  child = true;
}

declare function createInstance<T extends typeof Model>(
  model: T,
  data: Parameters<typeof Model.create<InstanceType<T>>>[0],
): InstanceType<T>;

const t = createInstance(Child, { title: "test", child: true });

Does this achieve the functionality you desire? https://tsplay.dev/m0Dbxm

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

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

Locating a specific entry in a custom object array based on a property

Currently working on an Angular 2 app using Typescript and encountering a challenge. There is a service that retrieves an array of questions structured like this: export class Question { constructor(public id: number, public quest ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Delete a particular instance of a component from an array within the parent component when a button is clicked within the child component, depending on a specific condition in Angular

One scenario I am facing involves the removal of a component instance from an array (located in the parent component) when a button is clicked inside the child component, based on a specific condition. https://i.sstatic.net/YPFHx.png Within the parent co ...

Leveraging the TypeScript compiler API to retrieve data on interface field types

Let's dive into the TypeScript compiler API to extract type information from a given interface: interface X { x: string } In this example, we are specifically interested in getting the type of property x. Here's a snippet of code showcasing ...

Combining two entities within nodeJS

Here is the setup I have: [{ "date": "2019-01-10T18:30:00.000Z", "time": "2019-01-11T04:37:49.587Z", "abc_Info": { "_id": "5c381da651f18d5040611eb2", "abc": 2.5, "guardian": "XYZ" } }] What I am aiming for: [{ "date": "2019-01-10T18:30:00.000Z" ...

Tips for preventing the "Too many re-renders" error in React and avoiding infinite loops

While utilizing react typescript, redux toolkit, and material UI together, I encountered an error when calling the API: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. at renderWithHooks () at mountIndeterminat ...

Angular: Populating a date field using a dropdown menu selection

Imagine there's a dropdown menu in my application, with options like "WORK", "RELEASE", and "OPEN". There's also a calendar field that is initially empty. When I choose the option "RELEASE" from the dropdown menu, I want it to automatically selec ...

Having trouble getting TypeScript to install using npm on a Mac?

My goal is to use Typescript as a local dependency by checking it into my devDependencies and using it via an npm script after installing it with 'npm install'. However, when I try this on my machine, I find that Typescript (and webpack-cli as w ...

In order to conceal the div tag once the animation concludes, I seek to implement React

I'm currently using the framer-motion library to add animation effects to my web page. I have a specific requirement where I want to hide a div tag used for animations once the animation is complete. Currently, after the animation finishes, the div t ...

Typescript extra property specifications

I need some assistance with creating a custom input field using typescript and Formik. Can someone please help me figure out how to include additional props like label & name in the code snippet below? I've been stuck on this for a while and I have a ...

Executing an infinite loop can occur when employing an NgRx call to dispatch an action within an Angular router

Story: Greetings to all! As a newcomer to using the NgRx library, I have encountered an issue in my Angular project where I am utilizing a router guard to prevent unauthorized users from accessing certain parts of the website. My approach involves callin ...

Filtering object properties from arrays in Angular HTML can be achieved using various methods such as

I am currently working on a unique "Presentation-Editor" tool where I can see all the presentations that have been created. For this overview, I want to showcase the first slide of each presentation as a preview. However, there is a challenge because I on ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Utilizing moment.js in conjunction with typescript and the module setting of "amd"

Attempting to utilize moment.js with TypeScript 2.1.5 has been a bit of a challenge for me. I went ahead and installed moment using npm : npm install moment --save-dev The d.ts file is already included with moment.js, so no need to install via @typings ...

unable to modify the attributes of an object in Angular

I've been tasked with modifying an existing Angular project that includes a component where I have the following variable: public testRunDetails: ITestRunDetails[] = []; The variable testRunDetails is of type ITestRunDetails, which is defined as: exp ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

What is the process for assigning the same type as one of the type members?

Consider the following code snippet: interface DbType { id: string, } interface RowType extends DbType { name: string } class MyDB<T extends DbType> { insert(item: T) { } delete(id: [typeof id]) { } } Let's say I create a n ...