{"id":1765,"date":"2023-10-12T10:09:25","date_gmt":"2023-10-12T10:09:25","guid":{"rendered":"https:\/\/palplanner.com\/schools\/?p=1765"},"modified":"2023-10-12T10:35:11","modified_gmt":"2023-10-12T10:35:11","slug":"title-typescript-decorators-in-practice-a-comprehensive-guide","status":"publish","type":"post","link":"https:\/\/palplanner.com\/schools\/title-typescript-decorators-in-practice-a-comprehensive-guide\/","title":{"rendered":"TypeScript Decorators in Practice: A Comprehensive Guide"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Introduction<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">TypeScript, a superset of JavaScript, provides a powerful set of tools for developers to write clean, maintainable, and scalable code. Among these tools, decorators stand out as a key feature that empowers developers to enhance and modify the behavior of classes, methods, properties, and more. In this article, we will explore TypeScript decorators in practice, their purpose, and how they can be used to streamline development, improve code readability, and maintain codebase consistency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Understanding TypeScript Decorators<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Decorators are a way to modify or extend the behavior of classes and class members in TypeScript. They are functions that are prefixed with the <code>@<\/code> symbol and applied to declarations, like classes, methods, and properties. Decorators can be used to augment or alter the functionality of the target they are applied to.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Common Use Cases for TypeScript Decorators<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Logging: Decorators can be used to log method calls, providing insight into when and how methods are executed. This is particularly useful for debugging and profiling code.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>function logExecution(target: any, key: string, descriptor: PropertyDescriptor) {\n  const originalMethod = descriptor.value;\n  descriptor.value = function (...args: any&#91;]) {\n    console.log(`Calling ${key} with arguments: ${args.join(', ')}`);\n    const result = originalMethod.apply(this, args);\n    console.log(`${key} returned: ${result}`);\n    return result;\n  };\n  return descriptor;\n}\n\nclass Calculator {\n  @logExecution\n  add(a: number, b: number) {\n    return a + b;\n  }\n}\n\nconst calculator = new Calculator();\ncalculator.add(2, 3);<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"2\">\n<li>Validation: Decorators can be used to validate the input of methods or properties. This is especially useful for ensuring that data meets specific criteria before processing.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>function validateStringLength(minLength: number, maxLength: number) {\n  return function (target: any, key: string, descriptor: PropertyDescriptor) {\n    const originalMethod = descriptor.value;\n    descriptor.value = function (value: string) {\n      if (value.length &lt; minLength || value.length &gt; maxLength) {\n        throw new Error(`Invalid ${key} length.`);\n      }\n      return originalMethod.call(this, value);\n    };\n    return descriptor;\n  };\n}\n\nclass User {\n  @validateStringLength(3, 30)\n  name: string;\n\n  constructor(name: string) {\n    this.name = name;\n  }\n}\n\nconst newUser = new User(\"John\");\nnewUser.name = \"J\"; \/\/ Throws an error<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li>Dependency Injection: Decorators can be used to facilitate dependency injection by automatically injecting required services or dependencies into a class or method.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>class UserService {\n  getUserData() {\n    return \"User data from the service.\";\n  }\n}\n\nfunction inject(service: any) {\n  return function (target: any, key: string) {\n    Object.defineProperty(target, key, {\n      get: () =&gt; new service(),\n    });\n  };\n}\n\nclass UserProfile {\n  @inject(UserService)\n  userData: UserService;\n\n  displayUserData() {\n    console.log(this.userData.getUserData());\n  }\n}\n\nconst userProfile = new UserProfile();\nuserProfile.displayUserData(); \/\/ Outputs \"User data from the service.\"<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li>Authorization: Decorators can be used to enforce authorization checks on methods or properties, ensuring that only authorized users can access certain functionalities.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>function authorize(roles: string&#91;]) {\n  return function (target: any, key: string, descriptor: PropertyDescriptor) {\n    const originalMethod = descriptor.value;\n    descriptor.value = function (...args: any&#91;]) {\n      if (isUserAuthorized(roles)) {\n        return originalMethod.apply(this, args);\n      } else {\n        throw new Error(\"Unauthorized access\");\n      }\n    };\n    return descriptor;\n  };\n}\n\nclass AdminPanel {\n  @authorize(&#91;\"admin\"])\n  deleteUserData() {\n    \/\/ Implementation to delete user data\n  }\n}\n\nconst adminPanel = new AdminPanel();\nadminPanel.deleteUserData(); \/\/ Executes only if authorized<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Creating Custom Decorators<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Creating custom decorators involves defining a function that takes target, key, and descriptor arguments and returns a new descriptor with the desired modifications. You can then apply these decorators to your classes and class members.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function myCustomDecorator(target: any, key: string, descriptor: PropertyDescriptor) {\n  \/\/ Custom decorator logic here\n  return descriptor;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Conclusion<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">TypeScript decorators are a powerful feature that can significantly improve the quality and maintainability of your code. They provide a flexible way to add, modify, or remove behavior from classes and their members, making it easier to implement cross-cutting concerns like logging, validation, dependency injection, and authorization.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By understanding and effectively utilizing decorators in your TypeScript projects, you can create cleaner, more organized, and more maintainable codebases. So, whether you&#8217;re building web applications, backend services, or any other TypeScript project, decorators are a valuable tool to have in your development toolbox.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction TypeScript, a superset of JavaScript, provides a powerful set of tools for developers to write clean, maintainable, and scalable code. Among these tools, decorators stand out as a key feature that empowers developers to enhance and modify the behavior of classes, methods, properties, and more. In this article, we will explore TypeScript decorators in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[29],"class_list":["post-1765","post","type-post","status-publish","format-standard","hentry","category-programming","tag-typescript"],"_links":{"self":[{"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/posts\/1765","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/comments?post=1765"}],"version-history":[{"count":2,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/posts\/1765\/revisions"}],"predecessor-version":[{"id":1796,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/posts\/1765\/revisions\/1796"}],"wp:attachment":[{"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/media?parent=1765"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/categories?post=1765"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/palplanner.com\/schools\/wp-json\/wp\/v2\/tags?post=1765"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}