JavaScript Development Space

Master TypeScript Decorators Quickly

Decorators in TypeScript are functions applied at runtime to classes or methods to modify or extend behavior.

Enabling Decorators

To enable experimental support, add this setting to your tsconfig.json or via CLI:

json
1 {
2 "compilerOptions": {
3 "target": "ES5",
4 "experimentalDecorators": true
5 }
6 }

Class Decorators

Class decorators modify the class constructor and prototype:

ts
1 function sealed(constructor: Function) {
2 Object.seal(constructor);
3 Object.seal(constructor.prototype);
4 }
5
6 @sealed
7 class BugReport {
8 // class logic
9 }

Method Decorators

These wrap method properties and can adjust visibility or behavior:

ts
1 function enumerable(value: boolean) {
2 return (target: any, key: string, descriptor: PropertyDescriptor) => {
3 descriptor.enumerable = value;
4 };
5 }
6
7 class Greeter {
8 @enumerable(false)
9 greet() {
10 return "Hello";
11 }
12 }

Property Decorators

These apply runtime modifications to class properties:

ts
1 class MyClass {
2 @MyDecorator
3 myProperty: string;
4 }

Decorators allow modular adjustments to class structure, method behavior, and property access, enhancing TypeScript's functionality in complex applications.

JavaScript Development Space

JSDev Space – Your go-to hub for JavaScript development. Explore expert guides, best practices, and the latest trends in web development, React, Node.js, and more. Stay ahead with cutting-edge tutorials, tools, and insights for modern JS developers. 🚀

Join our growing community of developers! Follow us on social media for updates, coding tips, and exclusive content. Stay connected and level up your JavaScript skills with us! 🔥

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.