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.

59 Comments

  1. Hiya, I am really glad I have found this info. Today bloggers publish just about gossips and net and this is really annoying. A good site with exciting content, this is what I need. Thanks for keeping this web site, I’ll be visiting it. Do you do newsletters? Can’t find it.

  2. Its like you learn my mind! You appear to understand so much approximately this, such as you wrote the ebook in it or something. I believe that you just can do with a few to force the message house a bit, but other than that, that is wonderful blog. A great read. I will certainly be back.

  3. Some really wonderful work on behalf of the owner of this web site, utterly great subject material.

  4. Just desire to say your article is as astounding. The clarity in your post is simply cool and i could assume you are an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.

  5. It’s hard to find knowledgeable people on this topic, but you sound like you know what you’re talking about! Thanks

  6. I’d must test with you here. Which is not something I often do! I take pleasure in studying a submit that can make folks think. Also, thanks for allowing me to remark!

  7. Its wonderful as your other content : D, appreciate it for posting. “To be at peace with ourselves we need to know ourselves.” by Caitlin Matthews.

  8. Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any feedback would be greatly appreciated.

  9. Real good information can be found on site. “I believe in nothing, everything is sacred. I believe in everything, nothing is sacred.” by Tom Robbins.

  10. I haven’t checked in here for a while since I thought it was getting boring, but the last several posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  11. Heya i’m for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you aided me.

  12. Thank you for helping out, good info. “Hope is the denial of reality.” by Margaret Weis.

  13. An attention-grabbing dialogue is value comment. I believe that you must write more on this subject, it won’t be a taboo topic however typically persons are not enough to speak on such topics. To the next. Cheers

  14. Whats Taking place i’m new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has helped me out loads. I hope to give a contribution & assist other customers like its aided me. Great job.

  15. Hello There. I discovered your blog using msn. This is a really well written article. I will be sure to bookmark it and return to read extra of your helpful information. Thanks for the post. I will definitely return.

  16. Magnificent web site. Lots of useful info here. I am sending it to a few friends ans additionally sharing in delicious. And naturally, thank you on your sweat!

  17. Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also

  18. Hello There. I found your weblog using msn. That is a very neatly written article. I will make sure to bookmark it and come back to learn extra of your helpful information. Thanks for the post. I’ll certainly return.

  19. Thanks for another informative web site. Where else could I get that type of info written in such a perfect way? I have a project that I am just now working on, and I have been on the look out for such info.

  20. Good blog! I really love how it is easy on my eyes and the data are well written. I’m wondering how I might be notified when a new post has been made. I’ve subscribed to your RSS feed which must do the trick! Have a great day!

  21. I have recently started a web site, the information you offer on this site has helped me greatly. Thank you for all of your time & work. “The word ‘genius’ isn’t applicable in football. A genius is a guy like Norman Einstein.” by Joe Theismann.

  22. Thanks for another informative website. Where else could I get that kind of info written in such a perfect way? I’ve a project that I am just now working on, and I’ve been on the look out for such info.

  23. Wow that was odd. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyway, just wanted to say great blog!

  24. I?¦ll immediately take hold of your rss feed as I can’t to find your email subscription hyperlink or e-newsletter service. Do you’ve any? Kindly let me realize so that I may just subscribe. Thanks.

  25. Wow, wonderful weblog structure! How long have you ever been blogging for? you made blogging glance easy. The overall glance of your website is wonderful, let alone the content!

  26. With havin so much written content do you ever run into any issues of plagorism or copyright violation? My blog has a lot of unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet without my permission. Do you know any methods to help protect against content from being stolen? I’d genuinely appreciate it.

  27. I wish to show appreciation to the writer just for bailing me out of this particular difficulty. Right after surfing around throughout the internet and finding suggestions which are not helpful, I was thinking my entire life was well over. Living devoid of the solutions to the difficulties you’ve fixed by means of the article is a crucial case, as well as ones which may have adversely affected my career if I hadn’t encountered your web site. Your main expertise and kindness in controlling the whole lot was valuable. I don’t know what I would have done if I hadn’t come upon such a subject like this. I can also at this time look forward to my future. Thanks very much for this skilled and result oriented guide. I will not think twice to endorse your web sites to any person who should get guidelines about this subject.

  28. I have been reading out a few of your posts and it’s pretty good stuff. I will make sure to bookmark your website.

  29. 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!

  30. 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!…

  31. 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.

  32. 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.

  33. Great work! This is the type of information that should be shared around the internet. Shame on the search engines for not positioning this post higher! Come on over and visit my website . Thanks =)

  34. Very well written article. It will be beneficial to anyone who usess it, as well as yours truly :). Keep up the good work – for sure i will check out more posts.

  35. Hiya, I’m really glad I’ve found this information. Today bloggers publish only about gossips and web and this is actually irritating. A good website with exciting content, that is what I need. Thank you for keeping this site, I’ll be visiting it. Do you do newsletters? Can’t find it.

  36. Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  37. Hey there! Someone in my Facebook group shared this website with us so I came to check it out. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Terrific blog and terrific style and design.

  38. hello there and thank you for your information – I’ve certainly picked up something new from right here. I did however expertise several technical issues using this site, as I experienced to reload the website lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage your quality score if ads and marketing with Adwords. Anyway I’m adding this RSS to my e-mail and could look out for a lot more of your respective interesting content. Ensure that you update this again very soon..

  39. I haven’t checked in here for a while since I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  40. I’m still learning from you, but I’m making my way to the top as well. I absolutely liked reading all that is written on your blog.Keep the information coming. I liked it!

  41. Thank you a lot for sharing this with all people you actually understand what you are speaking approximately! Bookmarked. Please additionally discuss with my web site =). We could have a hyperlink trade contract between us!

  42. I just could not depart your web site prior to suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts

  43. What i do not realize is in truth how you’re not actually much more smartly-liked than you might be now. You’re very intelligent. You understand thus considerably in relation to this topic, made me personally believe it from numerous various angles. Its like men and women don’t seem to be involved until it’s something to do with Lady gaga! Your individual stuffs great. Always care for it up!

  44. I believe other website owners should take this site as an example , very clean and superb user friendly design and style.

  45. I’m not sure where you’re getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for wonderful information I was looking for this info for my mission.

  46. Thank you, I have just been looking for info approximately this subject for a while and yours is the greatest I’ve discovered till now. But, what concerning the conclusion? Are you sure concerning the supply?

  47. I’m still learning from you, but I’m making my way to the top as well. I definitely liked reading everything that is written on your website.Keep the aarticles coming. I liked it!

Leave a Reply

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