You need to enable JavaScript to run this app. 如何使用TypeScript编译API生成Decorator及获取ts.Expression
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TypeScript编译API生成Decorator及获取ts.Expression

实现方案

你需要的ts.Expression实例本质就是装饰器对应的调用表达式节点,直接通过ts.factory提供的方法构造即可,完整流程如下:

1. 构造装饰器的调用表达式

以生成@IsString()、@Length(2, 10)两个class-validator装饰器为例,先构造对应的调用表达式节点:

import ts from "typescript";

// 生成@IsString()的表达式节点
const isStringExpr = ts.factory.createCallExpression(
  ts.factory.createIdentifier("IsString"), // 装饰器函数名
  undefined, // 无泛型参数时传undefined
  [] // 装饰器的入参,IsString无参数传空数组
);

// 生成@Length(2, 10)的表达式节点
const lengthExpr = ts.factory.createCallExpression(
  ts.factory.createIdentifier("Length"),
  undefined,
  [
    ts.factory.createNumericLiteral(2),
    ts.factory.createNumericLiteral(10)
  ]
);

2. 创建装饰器节点

将上面生成的表达式传入ts.factory.createDecorator即可得到装饰器实例:

const isStringDecorator = ts.factory.createDecorator(isStringExpr);
const lengthDecorator = ts.factory.createDecorator(lengthExpr);

3. 挂载装饰器到类属性

创建类属性节点时,将装饰器数组传入第一个参数位即可:

// 生成带装饰器的name属性
const nameProperty = ts.factory.createPropertyDeclaration(
  [isStringDecorator, lengthDecorator], // 装饰器数组
  ts.factory.createIdentifier("name"),
  undefined,
  ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
  undefined
);

// 把属性挂载到类上
const userClass = ts.factory.createClassDeclaration(
  undefined,
  ts.factory.createIdentifier("User"),
  undefined,
  undefined,
  [nameProperty]
);

额外注意

如果需要传入对象类型的装饰器参数,比如@IsOptional({ groups: ['update'] }),用ts.factory.createObjectLiteralExpression构造对象字面量作为入参即可。另外要记得同步生成class-validator的导入语句,否则运行时会找不到装饰器函数。

内容的提问来源于stack exchange,提问作者klaus bai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:18:01