TypeScript 元数据操作 API 及示例

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); // 输出: "Fetching user data"

示例 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); // 输出: [Function: String]

const paramTypes = Reflect.getMetadata("design:paramtypes", Example.prototype, "greet");
console.log(paramTypes); // 输出: [ [Function: String] ]

示例 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); // 输出: "1.0.0"

const httpMethod = Reflect.getMetadata("http-method", ApiController.prototype, "fetchData");
console.log(httpMethod); // 输出: "GET"

5. 应用场景

  • 依赖注入 (DI)
  • 序列化/验证
  • Web 框架路由
  • ORM 映射
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值