Decorators in TypeScript
Use decorators 到 annotate and 修改类, 方法, 属性, and 参数.
你将学到
- 什么 decorators 是 and 如何 启用它们 experimentally
- 类, 方法, 属性, and 参数 decorators
- Decorator factories for configurable decorators
- 常见 use 情况: logging, validation, and dependency injection
概念讲解
Enabling Decorators
Decorators are an experimental TypeScript feature (stage 3 in the TC39 process). Enable them with "experimentalDecorators": 真 in tsconfig.json. A decorator is a function prefixed with @ that is applied to a class, method, property, or parameter. Decorators run at class definition time and can observe, replace, or modify the target they are applied to.
The Four Decorator Types
Class decorators receive the constructor function and can replace it. Method decorators receive the target, method name, and descriptor, and can wrap or replace the method. Property decorators receive the target and property name. Parameter decorators receive the target, method name, and parameter index. Each type has a different signature and use case. Method decorators are the most common — used for logging, authorization, and caching.
Decorator Factories
A decorator factory is a function that returns a decorator. This lets you configure the decorator with arguments: @log("verbose") calls the factory with "verbose" to produce the actual decorator. Factories are how most real-world decorators work, from NestJS controllers (@Controller("/用户")) to class-validator properties (@IsEmail()). The factory pattern makes decorators reusable and configurable.
示例代码
// Enable: "experimentalDecorators": true in tsconfig.json
// Method decorator factory — logs method calls.
function log(prefix: string) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`[${prefix}] ${propertyKey}(${args.join(", ")})`);
return original.apply(this, args);
};
};
}
// Class decorator — marks a class as deprecated.
function deprecated(target: any) {
console.log(`Warning: ${target.name} is deprecated`);
}
@deprecated
class Calculator {
@log("MATH")
add(a: number, b: number): number {
return a + b;
}
@log("MATH")
multiply(a: number, b: number): number {
return a * b;
}
}
const calc = new Calculator();
console.log(calc.add(2, 3));
console.log(calc.multiply(4, 5));
Decorators (启用 使用 experimentalDecorators) annotate 类, 方法, 属性, and 参数. Decorator factories 返回 configurable decorators. 它们 是 widely used in 框架 如 NestJS and TypeORM.
动手试一试
- Code Diff
Compare code 使用 and 不使用 decorators 到 see transformation.
- Code Minifier
Observe 如何 decorators 编译 到 JavaScript helper 函数.
常见错误
错误写法
Using decorators 不使用 启用 experimentalDecorators in tsconfig
正确做法
Decorators 是 experimental. 设置 "experimentalDecorators": 真 in tsconfig.JSON compilerOptions. 不使用它, 编译器 reports 语法错误 on @ 语法.
错误写法
Confusing TypeScript decorators 使用 TC39 标准 decorator proposal
正确做法
TypeScript's experimental decorators 是 legacy 设计. TC39 标准 (stage 3) 有不同 API. 检查哪个 version 你的框架 expects 之前编写 decorators.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。