TypeScript / TypeScript Decorators and Metadata

Working with Decorators in TypeScript

This tutorial will introduce you to the concept of decorators in TypeScript. You will learn what decorators are, how to use them, and the different types of decorators available.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces decorators and metadata for advanced use cases in TypeScript applications.

Working with Decorators in TypeScript

1. Introduction

In this tutorial, we will explore decorators in TypeScript. Decorators are a significant feature of TypeScript that allow us to modify classes, properties, methods and accessor in a clean and readable way.

By the end of this tutorial, you will understand what decorators are, how to use them, and the various types of decorators available in TypeScript.

Prerequisites: Basic knowledge of TypeScript and object-oriented programming concepts.

2. Step-by-Step Guide

Decorators are special kinds of declarations in TypeScript. They are functions that can be attached to classes, methods, accessors, properties, or parameters. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated object.

There are four types of decorators in TypeScript:

  • Class Decorators
  • Method Decorators
  • Accessor Decorators
  • Property Decorators
  • Parameter Decorators

Class Decorators

A Class Decorator is declared just before a class declaration. The decorator function is applied to the constructor of the class and can be used to observe, modify or replace a class definition.

function sealed(constructor: Function) {
    Object.seal(constructor);
    Object.seal(constructor.prototype);
}

@sealed
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

In this example, @sealed is a class decorator and it 'seals' both the constructor and its prototype so that properties cannot be added or removed.

Method Decorators

Method Decorators are declared just before a method declaration. The decorator function is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.

function enumerable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.enumerable = value;
    };
}

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }

    @enumerable(false)
    greet() {
        return "Hello, " + this.greeting;
    }
}

In this example, @enumerable(false) is a method decorator and it sets the enumerable property of the greet method descriptor to false.

Accessor Decorators

Accessor Decorators are applied to the property descriptor of the accessor and can be used to observe, modify, or replace an accessor's definitions.

function configurable(value: boolean) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        descriptor.configurable = value;
    };
}

class Point {
    private _x: number;
    private _y: number;

    constructor(x: number, y: number) {
        this._x = x;
        this._y = y;
    }

    @configurable(false)
    get x() { return this._x; }

    @configurable(false)
    get y() { return this._y; }
}

In this example, @configurable(false) is an accessor decorator and it sets the configurable property of the x and y accessor descriptors to false.

3. Code Examples

Property Decorators

A Property Decorator is declared just before a property declaration. The decorator function is applied to the property descriptor for the property, and can be used to observe, modify, or replace a property definition.

function format(target: any, propertyKey: string) {
    let _val = target[propertyKey];
    let getter = function () {
        return "£" + _val;
    };
    let setter = function (newVal) {
        _val = newVal;
    };
    if (delete target[propertyKey]) {
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    }
}

class Product {
    @format
    price: number;
}

In this example, @format is a property decorator and it modifies the price property to always return its value prefixed with '£'.

Parameter Decorators

Parameter Decorators are declared just before a parameter declaration. The decorator function is applied to the function for a class constructor or method declaration.

function logParameter(target: any, propertyKey: string, parameterIndex: number) {
    let metadataKey = `log_${propertyKey}_parameters`;
    if (Array.isArray(target[metadataKey])) {
        target[metadataKey].push(parameterIndex);
    }
    else {
        target[metadataKey] = [parameterIndex];
    }
}

class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet(@logParameter name: string) {
        console.log("Greeting: " + name);
    }
}

In this example, @logParameter is a parameter decorator and it creates a metadata entry that records which parameters of the greet method should be logged.

4. Summary

Decorators are a powerful way to annotate or modify classes and class members. They provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are currently a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript.

5. Practice Exercises

  1. Create a class decorator that will log whenever an instance of the class is created.

  2. Create a method decorator that will log whenever the method is called.

  3. Create a property decorator for a class that has a 'price' property. The decorator should double the price whenever it is set.

Solutions and explanations will be provided in the comments. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help