Decorators: A Handy Tool for Renaming Instance Keys

I have a scenario where I have a class defined as follows:

class A {
  description: string
}

My requirement is that when creating an instance of this class, I want to set the description attribute. However, when accessing the instance of the class, I would like to use a.desc.

The usual approach for this would be something like:

class A {
  desc: string
  constructor(description: string) {
    this.desc = description
  }
}
const instance = new A("xxx xxx xxx")
console.log(instance) // { desc: "xxx xxx xxx" }
console.log(instance) // "xxx xxx xxx"

I was wondering if there is a way to achieve this using decorators like below:

class A {
  @RenameKey("desc")
  description: string
}

I came across the @Expose() decorator, but it changes both the input and output property names. What I am looking for is to keep the input property name as description while having the output as desc.

So my question is: Can we rename the keys of a class instance using decorators?

const a = new A("xxx xxx xxx")
a.desc = a.description
delete a.description

Although the above code snippet achieves what I want, I am interested in exploring decorator-based solutions.

Answer №1

After some exploration, I stumbled upon a clever solution utilizing the power of class-transformer, with an interesting twist.

  1. To make it work, define your class and apply the @Expose() decorator, setting the toPlainOnly property to true
class B {
 @Expose({ name: 'details', toPlainOnly: true })
  info: string
}
  1. Instantiate the class:
const z = plainToInstance(B, { info: "information here" })
  1. Convert the instance back to a plain object:
const w = instanceToPlain(z, {})
console.log(w) // { details: "information here" } ✅ success!

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

"A collection of elements in Typescript that is uniform in type, denoted by

Is it possible to declare an array of type any[] where all elements are of the same type? For example: // Allowed const array1: any[] = [1, 2, 3]; const array2: any[] = ['a', 'b', 'c']; // Not allowed because it contains bot ...

Exploring Real-Time Typescript Validation in Next.JS

Checking for TypeScript errors in Next.JS can only be done with npm run build (or yarn build). Unfortunately, running npm run dev won't display TypeScript errors, which is quite inconvenient as it would be better to have them visible in the Terminal ...

When object signatures match exactly, TypeScript issues a warning

I am facing an issue with typescript while trying to use my own custom type from express' types. When I attempt to pass 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' as a parameter of type 'Context&a ...

What is the best way for me to examine [...more] closely?

import * as Joi from 'joi'; import 'joi-extract-type'; const schema = { aaaaaaa: Joi.number() .integer() .positive() .allow(null), bbbbbb: Joi.number() .integer() .positive() .all ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

The issue arises in ts-jest nestjs where there is an attempt to access properties of an undefined

Creating an application using NestJS and utilizing ts-jest for e2e testing. For the code repository, visit: https://github.com/redplane/jest-issue A controller is set up with the following structure: @Controller({ path: 'api/shape', scope: S ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

How to Validate Comma-Separated Email IDs Using Regex in Angular 5 Template?

I am currently working on a project utilizing Angular 5. Within this project, there is an input field designated for E-Mail IDs. The main goal I aimed to achieve was: To enable the user to input a maximum of 3 E-Mail IDs, with each E-Mail ID being subject ...

Is there a method in TypeScript to retrieve property names from an interface resembling reflections in C#?

I am working with an interface in TypeScript/Angular that has various properties. I'm curious if there is a way to access the property names within the code. Here's an example of what my interface looks like: export interface InterfaceName ...

How to generate a SAS token or URL for a blob in React?

Hey there! I'm working on a React app that's written in TypeScript. I need to retrieve the document name as a query parameter and then get the SAS URL of the document for additional processing. Do you have any suggestions on how I can accomplish ...

How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data. In my component.ts file: import { HttpClient } from "@angular/common/http"; import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/fo ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

What is the reason behind TS not using Symbols for enums?

When it comes to enums, ES6 symbols provide a great solution for avoiding collisions. Initially, I assumed that TypeScript's enum type used Symbols for enums if the target was set to 'es6', but it turns out it doesn't: enum Role {Emplo ...

TypeScript utility function that retrieves properties from an interface based on a specified type

Is there a way to create a new object type that includes only properties from another Object that match specific types, as opposed to property names? For example: interface A { a: string; b: number; c: string[]; d: { [key: string]: never }; } int ...

Oops! There seems to be a syntax error near "NOT" in TypeORM

I am currently developing an app using NestJs with a Postgres database and TypeOrm as the ORM. I have created my migration file, configured the package.json file, but when I try to run yarn typeorm migration:run, I encounter the following error: query fail ...

Create an array with individual key-type pairs for each generic element, then iterate through the array

Consider the enum and type declarations in the code below: enum MyEnum { FIRST, SECOND }; type MyType = { firstKey: string | null, secondKey: boolean, thirdKey: MyEnum } Next, a variable is declared using the type as follows: let glob ...

The "if(x in obj)" statement in Typescript does not properly narrow down my custom Record

I am struggling with a code snippet where I am trying to check if a string exists in my custom record using the if(x in obj) guard statement, but it seems to not be working as expected. Below is the sample code snippet that is throwing an error: type Ans ...

Steps for utilizing an `<a>` link tag to submit a form in Angular 4

Is there a way to retrieve the selected option in this form from the other side when clicking a link? <form (ngSubmit)="onSubmit(x)"> <input type="radio" id="radioset3" name="radioset" [checked]="x==0"> <input type="radio" id="radio ...

The parameter type 'Element | null' cannot be assigned to the type 'Element | VirtualElement'

I am facing some difficulties in correctly typing this code as I keep encountering an error when using the popper component. The documentation is not very clear and my experience with Typescript is limited. The error message reads: "Argument of type &apo ...