Angular/TypeScript中如何在类装饰器内获取类构造函数参数
Angular + TypeScript 类装饰器获取构造函数参数问题
核心场景
- 项目技术栈为Angular + TypeScript
- 核心诉求:在自定义类装饰器内部,读取被装饰类构造函数的入参(即示例中
SomeClass构造函数定义的arg1),预期实现形式为直接访问构造函数对象挂载的arguments属性拿到参数列表。
现有代码基础
自定义装饰器初始实现
function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) { console.log("-- decorator function invoked --"); return class extends constructor { } }
装饰器使用方式
@ClassDecorator() export class SomeClass { // 目标:在ClassDecorator内部访问该构造函数的入参arg1 constructor(arg1) {} }
已尝试的无效方案与报错
此前通过直接访问构造函数挂载的arguments属性尝试获取参数,实现代码如下:
// 尝试通过原型链访问arguments export function ClassDec(ctor: Function) { ctor.prototype; console.log(' ctor.prototype :', ctor.prototype.arguments); } // 尝试在装饰器工厂阶段提前获取构造引用读取参数 export function ClassDec(target: Function) { console.log(target.arguments); return (constructor: Function) => { console.log(constructor, target.arguments); }; }
- 固定报错:访问
arguments属性时,TypeScript编译产出严格模式下的ES6类语法,会直接抛出语法错误,提示严格模式下无法访问arguments。 - 预期目标实现形式:
function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) { console.log("-- decorator function invoked --"); // 期望直接通过该语句拿到构造参数列表 console.log(constructor.prototype.arguments) return class extends constructor { } }
可行性结论
你当前尝试的、直接通过访问构造函数挂载的arguments属性读取构造参数的思路,完全走不通,核心原因有两个:
arguments是函数被调用时生成的内部上下文变量,从来不是函数/构造函数对象的可公开访问属性。ES6 之后的类语法默认运行在严格模式下,会直接禁用遗留的非标准Function.arguments属性访问,无论怎么写代码,只要在严格模式下访问该属性,就会直接抛出语法错误,没有任何合法的绕过路径。- 类装饰器的触发时机是类定义刚完成、还从来没有被实例化过的阶段。这个时候构造函数压根没被调用过,自然不存在任何传入的构造参数值,不管用什么反射技巧,都不可能读到一个从未存在过的东西。
补充说明:如果你的需求不是获取实例化时传入的运行时实参值,只是想拿到构造函数定义的参数类型列表,可以开启TypeScript的
emitDecoratorMetadata编译配置,从反射元数据中读取构造函数的参数类型信息,但这和你当前写的constructor.prototype.arguments的逻辑完全无关,也满足不了你读取构造入参的原始诉求。
内容的提问来源于stack exchange,提问作者mx_code
相关产品推荐
相关产品推荐

