Creating a versatile class by extending a mixin in TypeScript

Being relatively new to TypeScript, I'm looking to initialize an object for response data as shown below:

const auth = new ResponseData<Clazz>();

I have a mixin called BaseResponseHelper as follows:

type Constructor<T = object> = new (...args: any[]) => T;

export function BaseResponseHelper<TBase extends Constructor>(Base: TBase, options?: ApiPropertyOptions | undefined) {
  class ResponseDTO {
    @ApiProperty({ description: 'API execution error code', example: '0000' })
    @IsString()
    error_code!: string;

    @ApiProperty({
      description: 'Error code content',
      example: '[XXXX]Successfully executed',
    })
    @IsString()
    error_desc!: string;

    @ApiProperty({
      description: 'API execution status',
      example: true,
    })
    @IsBoolean()
    success!: boolean;

    @ApiProperty({
      isArray: true,
      type: () => Base,
      example: () => Base,
      description: 'Structure of returned data',
      ...options,
    })
    @Type(() => Base)
    @ValidateNested({ each: true })
    data_list!: Array<InstanceType<TBase>>;
  }
  return mixin(ResponseDTO); 
}

I tried implementing a class like this but encountered issues:

export class ResponseData<T> extends BaseResponseHelper(T) {}

Any suggestions on how to pass generic types in the ResponseData.ts file?

Appreciate your help!

export class ResponseData<T> extends BaseResponseHelper(T) {}

Answer №1

Have you checked out this page? https://www.typescriptlang.org/docs/handbook/mixins.html

In order to use a generic type for both the base class and extended object, consider the following approach:

export class ResponseData<T> extends BaseResponseHelper<T> {}

It's worth noting that if you're utilizing mixins and BaseResponseHelper is a function, you'll need to write something like this at some point:

class MyBaseClass
const ResponseData = BaseResponseHelper(MyBaseClass, options)

Alternatively, if you intend to implement hybrid types, refer to: https://www.typescriptlang.org/docs/handbook/interfaces.html#hybrid-types

Be sure to clearly define your objective in using these techniques.

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

Issue with noUnusedLocals flag detection within function* block

Compiler options: "noUnusedLocals": true, "noUnusedParameters": true, are not functioning properly within functions. An error is encountered in the following example: export class AllReduxSagas { [ts] Property 'someService' is declared bu ...

Understanding the implementation of public and private methods in mixins in Vue2

While I've come across documentation on the following implementation, I find myself struggling to visualize how it can be executed. // A more advanced alternative! var myGreatMixin = { // ... methods: { publicMethod() { // ... myPr ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

How to effectively filter a JSON array using multiple keys?

I need help filtering my JSON data by finding the objects with key 'status' equal to 'p' within the lease array. I attempted to use the following function, but it did not achieve the desired result: myActiveContractItems.filter((myActiv ...

What is the meaning of boolean true in a Firestore query using TypeScript?

Currently, I am facing an issue with querying Firestore in Angular 8 using AngularFire. While querying a string like module_version works perfectly fine as shown in the code snippet below, the problem arises when attempting to query a boolean field in Fire ...

Defining a generic type for a value in JSDoc

Currently, I am working on a project where I utilize JSDoc for type annotations and typescript definition files to simplify the creation of those types. As part of this process, I am transitioning some generic types from JSDoc to typescript due to its ease ...

What is the process of extending a class in TypeScript?

I have a few services that contain the same code: constructor (private http: Http) { //use XHR object let _build = (<any> http)._backend._browserXHR.build; (<any> http)._backend._browserXHR.build = () => { let _xhr = _ ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Updating an image in Angular 6

I am currently working with Angular 6 and Firebase. I am looking to update an image on the server. Here is a snippet of my HTML: <div class="form-check"> <input type="file" (change)="onFileSelected($event)"> </div> This is the va ...

The issue persists with react-hook-form and Material UI RadioGroup as the selected value remains null

Having trouble with RadioGroup from Material UI when using react-hook-form Controller. I keep getting a null selected value, even though my code seems right. Can you help me figure out what's missing? import * as React from "react"; import { ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

Updating the parent navigation bar after a successful login in a child component in Angular4

In my Angular4 project, I have set up a login page. Within the parent app.component file, I have included a navigation bar with login and signup buttons. Upon successful login, the login and signup buttons should be hidden, and the username should appear i ...

Struggling to use the bind method for the loadScene callback function in cocosCreator or cocos2d-x?

When the loadScene() callback function is bound, the information retrieved from getScene() becomes inaccurate. Upon transitioning from the Entry Scene to the Lobby Scene, I perform post-processing tasks. The implementation was done in TypeScript. Entry. ...

Create the HTTP POST request body using an object in readiness for submission

When sending the body of an http post request in Angular, I typically use the following approach: let requestBody: String = ""; //dataObject is the object containing form values to send for (let key in dataObject) { if (dataObject[key]) { ...

Can you explain the concept of `export as namespace` in a TypeScript definition file?

While browsing through some declaration files on DefinitelyTyped, I have noticed the following pattern: declare function domready(callback: () => any) : void; export = domready; export as namespace domready; I am familiar with the first two lines - d ...

How can I achieve a result using a floating label in a .ts file?

I'm facing a simple issue that I can't seem to figure out. The problem is with a floating label in my HTML file, as shown below: <ion-list> <ion-item> <ion-label floating >Username</ion-la ...

`Designing a UI in Ionic version 2`

Is it possible to create a layout page in an Ionic v2 application so that the navbar and sidemenu can be displayed on every page without having to add them individually to each page? For example, ASP.NET uses master pages for websites to contain component ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

Tips for concealing the delete button within the main content area and displaying it in the subsequent "add" pop-up window upon clicking the "add" button in Angular

I have a card with add and delete buttons. I want only the add button to show initially, and when clicked, a new card should open with both add and delete buttons. Everything is working as expected except I can't figure out how to hide the delete butt ...