Class Decorators in TypeScript

Mehran
2 min readApr 13, 2023
Generated using Lexica

The Class decorators in TypeScript are a way to add metadata or behavior to a class at design time. They are functions executed when a class is declared and can be used to modify the class's constructor or prototype.

To use a class decorator, you apply the decorator function to the class definition using the @ symbol. Here's an example:

function myDecorator(target: any) {
// Do something with the target class
}

@myDecorator
class MyClass {
// Class implementation
}

In this example, the myDecorator function is applied to the MyClass class using the @ symbol. The function is passed the class constructor as its argument and can modify the class as needed.

Real-World Example

A real-world example of using class decorators in TypeScript is to add validation to a class. Let's say you have a Person type with firstName and lastName properties. You want to ensure that these properties are always set to a string value and are not empty.

You could accomplish this using a class decorator that adds validation to the constructor. Here's an example:

function validatePerson(target: any) {
const original = target;

// Define a new constructor that performs validation
function newConstructor(...args: any[]) {
for (const arg of args) {
if (typeof arg !== 'string' || arg === '') {
throw new Error('Invalid argument: expected a non-empty string');
}
}

// Call the original constructor with validated arguments
const instance = new original(...args);
return instance;
}

// Set the prototype of the new constructor to the original prototype
newConstructor.prototype = original.prototype;

// Return the new constructor
return newConstructor;
}

@validatePerson
class Person {
constructor(public firstName: string, public lastName: string) {}
}

In this example, the validatePerson the function is applied to the Person class using the @ Symbol. The function creates a new constructor that performs validation on the arguments passed to it and calls the original constructor with the validated arguments.

Now, when you create a new instance of the Person class, the constructor will validate the firstName and lastName arguments before creating the object. An error will be thrown if either argument is not a string or is an empty string.

const person = new Person('John', 'Doe'); // Valid
const invalidPerson = new Person('', ''); // Throws an error

This is just one example of how class decorators can be used to add behavior to a class at design time. With decorators, you can easily add functionality like validation, logging, or performance monitoring to your courses without cluttering your code with a boilerplate.

This example has helped you understand class decorators in TypeScript better!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Mehran
Mehran

Written by Mehran

Tech Team Lead | Cloud, Video & Microservices Expert | Insights on streaming innovations & programming. #ContinuousLearning

Responses (1)

Write a response