当前位置: 首页 > news >正文

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 映射
http://www.dtcms.com/a/109735.html

相关文章:

  • Unity HDRP管线用ShaderGraph还原Lit,方便做拓展;
  • 详解Pinctrl子系统
  • Redis 的 Raft 选举协议
  • 使用MFC ActiveX开发KingScada控件(OCX)
  • Mac Apple silicon如何指定运行amd64架构的ubuntu Docker?
  • 浅浅尝试Numpy的函数:
  • 【数据结构】排序算法(中篇)·处理大数据的精妙
  • git commit Message 插件解释说明
  • Ubuntu服务器挂载之前的数据硬盘
  • C++中的链表操作
  • 网络运维学习笔记(DeepSeek优化版)027 OSPF外部路由计算
  • GaussDB数据库SQL开发实践与性能优化全解析
  • 汇编学习之《jcc指令》
  • Vue 数据传递流程图指南
  • CompletableFuture:核心方法、应用场景
  • 面向对象软件开发与中国哲学的关系
  • Java面试题及答案整理( 2025年 4 月最新版,持续更新)
  • 每天10分钟!自动抓取并生成每日简报的AI方案
  • 从零开始训练Codebook:基于ViT的图像重建实践
  • 认识 Promise
  • 三、GPIO
  • 【上新了】深入理解 Java 虚拟线程:与传统线程的对比及应用
  • Vue2 监听器 watcher
  • qt tcpsocket编程遇到的并发问题
  • Spring Boot应用中实现Jar包热更新的实践指南
  • macOS设置定时播放眼保健操
  • Java的数据库编程——JDBC基础
  • 2025年AI技术十大趋势深度解析:从实验室到主流应用
  • 移动端六大语言速记:第6部分 - 错误处理与调试
  • CAS:47623-98-3,DiSBAC2(3)一种慢反应的膜电位敏感探针