How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status:

export enum Status {
  Active = "Active",
  Inactive = "Inactive",
}

Additionally, I have a UserStatus enum:

export enum UserStatus {
  Active = Status.Active,
};

There is also a common dto that includes the status:

export class CommonDto {

  @ApiProperty({ description: "Status", required: true })
  status: Status;

In my user dto, I extend this class like so:

export class UserDto extends CommonDto {

  @ApiProperty({ description: "Status", required: true, enum: UserStatus })
  status: UserStatus;

However, there seems to be an error:

Property 'status' in type 'UserDto' is not assignable to the same property in base type 'CommonDto'.
  Type 'UserStatus' is not assignable to type 'Status'

Can anyone provide assistance?

Answer №1

There are several approaches to addressing this issue.

The first method involves using generic classes

In this scenario, the type of the status generic is specified. This allows each class that extends from CommonDto to have its own unique status type.

export class CommonDto<T> {
  @ApiProperty({ description: "Status", required: true })
  status: T;
  // ...
}

export class UserDto extends CommonDto<UserStatus> {
  // ...
}

The second approach is utilizing union types

In TypeScript, multiple possible types can be set using union types:

export type AnyStatus = Status | UserStatus;

export class CommonDto {
  @ApiProperty({ description: "Status", required: true })
  status: AnyStatus;
  // ...
}

export class UserDto extends CommonDto {
  @ApiProperty({ description: "Status", required: true, enum: UserStatus })
  status: AnyStatus;
  // ...
}

The third option involves using intersected types

In TypeScript, properties can be "deleted" and "added" in extended classes to manipulate their types, as shown below:

type WithUserStatus<T> = Omit<T, 'status'> & { status: UserStatus };

type UserDto = WithUserStatus<CommonDto>;

Learn more about intersections here

These are potential solutions for your situation. It is recommended to define the status separately with its own type in each class (excluding the base class CommonDto).

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

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

What causes the variable to be invisible in the imported file?

Within the main.js file, there is a specific code snippet: var test_mysql = require('./test_mysql.js') ... //additional code before(function(){ test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL ...

Learning to handle data fetching and looping in NextJs

I'm facing an issue with fetching data through a loop in getStaticProps. The array ends up empty due to asynchronous code. If I pass the ID array and implement the logic within the React component, it works fine. Should I continue using the component ...

Exploring the use of barcodes with node.js

Having some issues with generating a barcode using a barcode module from NPMJS called npm i barcode. I am getting an error message res is not defined even after following the instructions. Can someone please guide me in the right direction? Here is my code ...

Tips for passing a variable after a redirect in res.render/send?

I am looking for a way to send a message variable indicating success or failure without relying on passport or sessions. If the login attempt fails, I can use this code: res.status(401).render('register', { message: 'Your username/email ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Tips for receiving responses when data is posted to a URL in Node.js using `req.body.url`

How can I retrieve data from the URL provided in req.body.url using Postman's collection tool? In my code snippet, I have defined a key as "URL" and the corresponding value as a live URL. You can refer to the screenshot below for more details: const ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

Exploring the comparison of information across two sets of databases using Node.js and MongoDB

In the realm of Node.js and MongoDB, I have set up two databases (1-btech2014 & 2-btechre2014) on a single server. My objective is to compare the data in btech2014 with that in btechre2014. If they match, I should retrieve the data from btech2014 as outpu ...

Currently awaiting the bundling process of webpack to be completed prior to initiating nodemon

Currently, I am working on a Node.js project written in Typescript. To transpile my code into JavaScript and bundle it into a server.js file (located in the dist folder), I have webpack set up with a Typescript loader. During development, both webpack and ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...

Using RxJS switchMap in combination with toArray allows for seamless transformation

I'm encountering an issue with rxjs. I have a function that is supposed to: Take a list of group IDs, such as: of(['1', '2']) Fetch the list of chats for each ID Return a merged list of chats However, when it reaches the toArray ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

Angular 2 view becomes unresponsive following navigation

I have a web application powered by an API using Angular 2. I implemented a global service that extends angular2-sails, which handles responses to API calls. If the response includes 401 PLEASE_LOGIN, it redirects the user to the signup component. The iss ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Firebase deployment encounters an error due to missing dependencies

I've run into an issue while trying to deploy a Firebase function. Despite my attempts to resolve it by deleting `node_modules` and `package-lock.json`, running `npm install`, and using `firebase deploy --only functions` multiple times, the build proc ...