Extracting Property Names from DTOs with TypeScript: A How-To Guide

Extracting Property Names from DTOs with TypeScript: A How-To Guide

Have you ever encountered a situation where you needed to extract the property names of Data Transfer Object (DTO) to an array for data manipulation. In these scenarios, knowing how to efficiently extract attributes from a DTO and convert them into an array becomes crucial.

This blog post explain an approach for extracting property names from DTOs and transforming them into arrays.

What are DTOs?

Boost your productivity! Upgrade your desk with the Simple Trending 2 Tier Metal Monitor Stand. Click here to buy on Amazon!

DTOs, or Data Transfer Objects, are lightweight objects employed in software development to encapsulate data for transfer between different layers of an application. They act as a bridge between presentation and persistence layers, carrying only the necessary data for the receiving layer to function. Think of them as streamlined data carriers specifically designed for communication within an application.

Check for more details…

Extracting DTO Property Names with TypeScript Decorators

Since TypeScript doesn’t natively support reflection on classes at runtime to list their properties, we’ll leverage a custom decorator to collect property names at design time. Here’s a step-by-step approach:

  • Define a decorator to collect property names.
  • Apply this decorator to the properties of ExampleDto.

First, create a file named collectKeysDecorator.ts and define the decorator to capture property names.

// collectKeysDecorator.ts
export function CollectKeys(target: any, propertyKey: string) {
    if (!target.constructor.propertyKeys) {
        target.constructor.propertyKeys = [];
    }
    target.constructor.propertyKeys.push(propertyKey);
}

This decorator targets both the class instance (target) and the property name (propertyKey). It checks if a static array named propertyKeys exists on the class constructor. If not, it creates the array. Finally, it pushes the current property name (propertyKey) onto the propertyKeys array.

Next, import and use this decorator in your class.

import { CollectKeys } from './collectKeysDecorator';

export class ExampleDto {
  static propertyKeys: string[] = [];// Static array to store property names

  constructor() {
        super();
  }

  @CollectKeys // Apply decorator to each property
  propertyOne: string

  @CollectKeys 
  propertTwo: number

  @CollectKeys 
  propertyThree: boolean

}

By applying the CollectKeys decorator to each property, you ensure that the property names are collected in the propertyKeys static array.

Then, create the method to get the property names.

export class ExampleService {
  getBaseProperties(class_name: any): string[] {
    return class_name.propertyKeys;
  }

  manipulateWithPropertyNames() {
    let propertyNames = this.getBaseProperties(ExampleDto);
    // Now you have an array of property names to use for manipulation
  }
}

The getBaseProperties method accepts a class reference (class_name) as a parameter and simply returns the propertyKeys static array from that class. This allows you to retrieve property names dynamically for any DTO class decorated with CollectKeys.

Key Points:

  • The CollectKeys decorator pushes property names to a static array propertyKeys defined on the DTO class.
  • getBaseProperties accesses the propertyKeys static array to get all property names dynamically.
  • Using static properties ensures that each class type has its own list of property names, preventing race conditions and data corruption.

Conclusion

By leveraging TypeScript decorators, you can effectively extract property names from DTO.

Happy Coding…

Subscribe

Enter your email below to receive updates.

5 Comments

  1. A powerful share, I simply given this onto a colleague who was doing a bit of evaluation on this. And he in truth purchased me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love reading extra on this topic. If possible, as you change into expertise, would you mind updating your weblog with extra particulars? It’s highly helpful for me. Large thumb up for this weblog submit!

  2. I found your weblog web site on google and verify a few of your early posts. Proceed to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Searching for forward to reading more from you in a while!…

  3. We’re a bunch of volunteers and opening a brand new scheme in our community. Your website provided us with useful information to paintings on. You have performed a formidable process and our whole community shall be thankful to you.

  4. Thanks for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such magnificent info being shared freely out there.

Leave a Reply

Your email address will not be published. Required fields are marked *