Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Decorators

TypeScript Decorators

Decorators are an experimental feature of TypeScript.

They allow developers to add extra functionality to classes, methods, properties, or parameters without modifying the original class.

A decorator is essentially a function that can be called at runtime to modify the behavior of the target object.

Decorator types and application positions @ClassDecorator Class decorators Property decorators @propertyDecorator Method decorators @methodDecorator Parameter decorators @paramDecorator Accessor decorators @getterDecorator Decorator factories A decorator factory is a function that returns a decorator function, configured through parameters For example: function color(code: string) { return function(target) { ... }; } → @color("34")

Introduction to decorators

Decorators use the @ symbol as syntactic sugar and can be attached to classes, methods, accessors, properties, or parameters.

This pattern is common in framework development; Angular, TypeORM, and others use decorators extensively for dependency injection, data validation, and more.

Note:Decorators are currently experimental and must be explicitly enabled in tsconfig.json. When using them in production, confirm your project's support for experimental features.


Enable decorators in configuration

Before using decorators, you need to enable the relevant compiler options in the TypeScript configuration file tsconfig.json.

tsconfig.json configuration

{

   

"compilerOptions"

:

{

       

// Enable decorator syntax

       

"experimentalDecorators"

:

true

,

       

// Enable decorator metadata (used by dependency injection frameworks)

       

"emitDecoratorMetadata"

:

true

   

}

}

Parameter Description:


Class decorators

Class decorators are applied to a class's constructor and can modify the class definition or add extra processing logic.

A class decorator receives one argument: the target class's constructor.

Basic usage of class decorators

// Define a class decorator function

// The target parameter is the decorated class's constructor

function

sealed

(

target

:

Function

)

{

   

// Print the name of the class the decorator is applied to

    console.

log

(

"Decorator applied to: "

target.

name

)

;

   

// Use Object.seal to lock the constructor and prototype

   

// Prevent adding or removing properties at runtime

   

Object

.

seal

(

target

)

;

   

Object

.

seal

(

target.

prototype

)

;

}

// Use the @ syntax to apply the decorator to the class

@

sealed

class

Person

{

    name

:

string

;

    constructor

(

name

:

string

)

{

       

this

.

name

=

name

;

   

}

}

// Create an instance to test

var

person

=

new

Person

(

"RUNOOB"

)

;

console.

log

(

"Created: "

person.

name

)

;

// Try to add a new property (blocked because the class is sealed)

// person.age = 25; // Fails silently

Running result:

装饰器 applied to: Person

创建: RUNOOB

Explanation:

Class decorators execute when the class is defined, usually to modify class behavior, add metadata, or implement AOP (aspect-oriented programming).


Method decorators

Method decorators are applied to a class's methods and can modify a method's Property Descriptor.

A method decorator receives three arguments: the target object, the property name, and the property descriptor.

Basic usage of method decorators

// Define a method decorator factory

// Return a decorator function

function

enumerable

(

value

:

boolean

)

{

   

// Return the decorator function, which receives three arguments

   

return

function

(

        target

:

any

,

         

// The prototype object of the containing class

        propertyKey

:

string

,

   

// The method name

        descriptor

:

PropertyDescriptor

// The property descriptor

   

)

{

       

// Modify the enumerable attribute of the property

       

// false means the method is not enumerable

        descriptor.

enumerable

=

value

;

   

}

;

}

class

Greeter

{

    greeting

:

string

;

    constructor

(

message

:

string

)

{

       

this

.

greeting

=

message

;

   

}

   

// Apply the decorator, setting the method as non-enumerable

   

@

enumerable

(

false

)

    greet

(

)

{

       

return

"Hello, "

this

.

greeting

;

   

}

}

var

g

=

new

Greeter

(

"World"

)

;

// Check whether the greet method is enumerable

console.

log

(

"Method enumerable: "

g.

propertyIsEnumerable

(

"greet"

)

)

;

// Iterate over the object's properties

for

(

var

key

in

g

)

{

    console.

log

(

"Property: "

key

)

;

}

Running result:

方法可枚举: false

Tip:PropertyDescriptor contains attributes such as enumerable, configurable, writable, and value, which can be modified as needed.


Accessor decorators

Accessor decorators are applied to a class's getter and setter methods.

Like method decorators, accessor decorators can also modify a property descriptor.

Usage of accessor decorators

// Accessor decorator factory

function

configurable

(

value

:

boolean

)

{

   

return

function

(

        target

:

any

,

        propertyKey

:

string

,

        descriptor

:

PropertyDescriptor

   

)

{

       

// Modify the configurable attribute of the property

       

// false means the accessor cannot be reconfigured or deleted

        descriptor.

configurable

=

value

;

   

}

;

}

class

Point

{

    private _x

:

number

=

0

;

    private _y

:

number

=

0

;

   

// Use the decorator to lock the getter

   

@

configurable

(

false

)

   

get

x

(

)

{

       

return

this

._x

;

   

}

   

@

configurable

(

false

)

   

get

y

(

)

{

       

return

this

._y

;

   

}

   

set

x

(

value

:

number

)

{

       

this

._x

=

value

;

   

}

   

set

y

(

value

:

number

)

{

       

this

._y

=

value

;

   

}

}

var

point

=

new

Point

(

)

;

point.

x

=

10

;

point.

y

=

20

;

console.

log

(

"Coordinate: ("

point.

x

", "

point.

y

")"

)

;

Explanation:

An accessor decorator cannot be applied to both the getter and setter of the same property; you can only choose one.


Property decorators

Property decorators are applied to a class's property definitions.

A property decorator receives two arguments: the target object and the property name.

Usage of property decorators

// Property decorator factory

function

format

(

formatString

:

string

)

{

   

return

function

(

        target

:

any

,

         

// The class's prototype object

        propertyKey

:

string    

// The property name

   

)

{

       

// Store metadata on the target object

       

// Use propertyKey + "_format" as the key to avoid conflicts

       

Object

.

defineProperty

(

target

,

propertyKey

"_format"

,

{

            value

:

formatString

,

            writable

:

false

,

            enumerable

:

false

,

            configurable

:

true

       

}

)

;

   

}

;

}

class

User

{

   

// Apply the property decorator, specifying the date format

   

@

format

(

"YYYY-MM-DD"

)

    birthDate

:

string

;

    constructor

(

birthDate

:

string

)

{

       

this

.

birthDate

=

birthDate

;

   

}

}

var

user

=

new

User

(

"1990-01-01"

)

;

console.

log

(

"Birth date: "

user.

birthDate

)

;

// Access the stored metadata

console.

log

(

"Date format: "

(

user as any

)

.

birthDate_format

)

;

Running result:

出生日期: 1990-01-01

日期格式: YYYY-MM-DD


Parameter decorators

Parameter decorators are applied to a class method's parameters and can add metadata or markers to a parameter.

A parameter decorator receives three arguments: the target object, the method name, and the parameter's index in the function.

Usage of parameter decorators

// Parameter decorator

// Used to log parameter information or perform validation

function

logParameter

(

    target

:

any

,

             

// The class's prototype object

    propertyKey

:

string

,

     

// The method name

    parameterIndex

:

number    

// The parameter's index in the function (starting from 0)

)

{

    console.

log

(

"Parameter decorator: "

propertyKey

       

" #"

(

parameterIndex

1

)

" parameter"

)

;

}

class

Greeter

{

    greeting

:

string

;

    constructor

(

greeting

:

string

)

{

       

this

.

greeting

=

greeting

;

   

}

   

// Use the @ syntax before the parameter to apply the decorator

    greet

(

@

logParameter name

:

string

)

{

       

return

this

.

greeting

", "

name

;

   

}

}

var

greeter

=

new

Greeter

(

"Hello"

)

;

greeter.

greet

(

"RUNOOB"

)

;

Running result:

参数装饰器: greet 第 1 个参数


Decorator factories

A decorator factory is a function that returns a decorator function.

With a decorator factory, you can pass custom arguments when applying a decorator for more flexible configuration.

Decorator factory implementing colored logging

// Decorator factory: receives configuration parameters and returns a decorator function

function

color

(

colorCode

:

string

)

{

   

// colorCode is the ANSI escape sequence color code

   

// For example: 34 = blue, 31 = red, 32 = green

   

return

function

(

        target

:

any

,

        propertyKey

:

string

,

        descriptor

:

PropertyDescriptor

   

)

{

       

// Save the original method

       

var

originalMethod

=

descriptor.

value

;

       

// Override the method to add color

        descriptor.

value

=

function

(

...

args

:

any

[

]

)

{

           

// Call the original method to get its return value

           

var

result

=

originalMethod.

apply

(

this

,

args

)

;

           

// If in a terminal environment, add color to the output

           

// ANSI escape sequence format: \x1b[color-code m content \x1b[0m

           

return

"\x1b["

colorCode

"m"

result

"\x1b[0m"

;

       

}

;

   

}

;

}

class

Logger

{

   

// Use the decorator factory, passing blue code 34

   

@

color

(

"34"

)

    log

(

message

:

string

)

:

string

{

       

return

message

;

   

}

   

@

color

(

"31"

)

    error

(

message

:

string

)

:

string

{

       

return

message

;

   

}

   

@

color

(

"32"

)

    success

(

message

:

string

)

:

string

{

       

return

message

;

   

}

}

var

logger

=

new

Logger

(

)

;

console.

log

(

logger.

log

(

"This is a blue log"

)

)

;

console.

log

(

logger.

error

(

"This is a red error"

)

)

;

console.

log

(

logger.

success

(

"This is a green success"

)

)

;

Running result:

这是蓝色日志(终端显示为蓝色)

这是红色错误(终端显示为红色)

这是绿色成功(终端显示为绿色)

Explanation:Decorator factories are the most commonly used form in real development; they let you pass arguments when applying a decorator for configurable behavior.


Decorator execution order

When a class has multiple decorators, execution follows specific rules.

Decorator execution order example

// Stack multiple decorators

function

first

(

)

{

    console.

log

(

"first decorator"

)

;

   

return

function

(

target

:

any

)

{

        console.

log

(

"first decorator function"

)

;

   

}

;

}

function

second

(

)

{

    console.

log

(

"second decorator"

)

;

   

return

function

(

target

:

any

)

{

        console.

log

(

"second decorator function"

)

;

   

}

;

}

@

first

(

)

@

second

(

)

class

MyClass

{

    name

:

string

;

}

var

obj

=

new

MyClass

(

)

;

Running result:

second 装饰器

first 装饰器

second 装饰器函数

first 装饰器函数

Explanation:

Decorator functions are defined (console.log) first, then executed from bottom to top.


Practical Application Scenarios

Decorators have a wide range of applications in real projects.

Logging

Automatically log method calls.

Example

// Logging decorator

function

log

(

target

:

any

,

propertyKey

:

string

,

descriptor

:

PropertyDescriptor

)

{

   

var

originalMethod

=

descriptor.

value

;

    descriptor.

value

=

function

(

...

args

:

any

[

]

)

{

        console.

log

(

"Method called: "

propertyKey

", args: "

JSON.

stringify

(

args

)

)

;

       

var

result

=

originalMethod.

apply

(

this

,

args

)

;

        console.

log

(

"Method returned: "

JSON.

stringify

(

result

)

)

;

       

return

result

;

   

}

;

}

class

MathService

{

   

@

log

    add

(

a

:

number

,

b

:

number

)

:

number

{

       

return

a

b

;

   

}

   

@

log

    multiply

(

a

:

number

,

b

:

number

)

:

number

{

       

return

a

b

;

   

}

}

var

math

=

new

MathService

(

)

;

console.

log

(

"Calculation result: "

math.

add

(

5

,

3

)

)

;

Running result:

调用方法: add,参数: [5,3]

方法返回: 8

计算结果: 8

Permission validation

Implement method-level permission checks.

Example

// Simulate the current user's role

var

currentUser

=

{

role

:

"admin"

}

;

// Permission decorator

function

requireRole

(

role

:

string

)

{

   

return

function

(

target

:

any

,

propertyKey

:

string

,

descriptor

:

PropertyDescriptor

)

{

       

var

originalMethod

=

descriptor.

value

;

        descriptor.

value

=

function

(

...

args

:

any

[

]

)

{

           

if

(

currentUser.

role

!==

role

)

{

                console.

log

(

"Insufficient permission, cannot execute "

propertyKey

)

;

               

return

null

;

           

}

           

return

originalMethod.

apply

(

this

,

args

)

;

       

}

;

   

}

;

}

class

AdminService

{

   

@

requireRole

(

"admin"

)

    deleteUser

(

id

:

number

)

:

string

{

       

return

"Delete user "

id

" succeeded"

;

   

}

   

@

requireRole

(

"admin"

)

    viewUser

(

id

:

number

)

:

string

{

       

return

"View user "

id

;

   

}

}

var

admin

=

new

AdminService

(

)

;

console.

log

(

admin.

viewUser

(

1

)

)

;

console.

log

(

admin.

deleteUser

(

1

)

)

;

// Simulate a regular user

currentUser

=

{

role

:

"user"

}

;

console.

log

(

admin.

deleteUser

(

2

)

)

;

Running result:

查看用户 1

删除用户 1 成功

权限不足,无法执行 deleteUser


Notes

Note:When using decorators in a project, it is recommended to create dedicated decorator utility classes or function libraries to manage decorator definitions and usage centrally.


Summary

TypeScript decorators provide powerful metaprogramming capabilities.