TypeScript 元数据操作 API 及示例
1. 配置环境
安装依赖
npm install reflect-metadata
tsconfig.json 配置
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "ES6"
}
}
2. 元数据操作 API
Reflect.defineMetadata(key, value, target, propertyKey?)
Reflect.getMetadata(key, target, propertyKey?)
Reflect.hasMetadata(key, target, propertyKey?)
Reflect.getMetadataKeys(target, propertyKey?)
3. 内置元数据键
design:type
:属性/方法的类型design:paramtypes
:方法参数的类型design:returntype
:方法返回值类型
4. 示例代码
示例 1:自定义装饰器
import "reflect-metadata";
function LogInfo(message: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Reflect.defineMetadata("log-message", message, target, propertyKey);
};
}
class UserService {
@LogInfo("Fetching user data")
getUser(id: number) {
return { id, name: "Alice" };
}
}
const message = Reflect.getMetadata("log-message", UserService.prototype, "getUser");
console.log(message);
示例 2:内置元数据推断
import "reflect-metadata";
class Example {
@Reflect.metadata("custom-prop", true)
public name: string = "";
greet(@Reflect.metadata("required", true) name: string): string {
return `Hello, ${name}`;
}
}
const propType = Reflect.getMetadata("design:type", Example.prototype, "name");
console.log(propType);
const paramTypes = Reflect.getMetadata("design:paramtypes", Example.prototype, "greet");
console.log(paramTypes);
示例 3:类级别元数据
import "reflect-metadata";
@Reflect.metadata("api-version", "1.0.0")
class ApiController {
@Reflect.metadata("http-method", "GET")
public fetchData() {}
}
const apiVersion = Reflect.getMetadata("api-version", ApiController);
console.log(apiVersion);
const httpMethod = Reflect.getMetadata("http-method", ApiController.prototype, "fetchData");
console.log(httpMethod);
5. 应用场景
- 依赖注入 (DI)
- 序列化/验证
- Web 框架路由
- ORM 映射