如何在类方法的装饰器中访问该类的静态成员?
问题描述
想要用TypeScript 5.0新装饰器API,让类方法自动使用同类中指定的静态属性作为参数。当前实现的装饰器无法访问目标静态属性,调用方法时newArgs为undefined。
原装饰器代码:
type TargetFunction<This, Args extends unknown[], Return> = (this: This, ...args: Args) => Return; class Throwable extends Error {} // 仅用于演示 export interface ITestParameters { dataProvider?: string; expectedExceptions?: typeof Throwable; } export const Test = <T extends ITestParameters>(param: T) => { return <This, Args extends unknown[], Return>(target: TargetFunction<This, Args, Return>, context: ClassMethodDecoratorContext<This, TargetFunction<This, Args, Return>>) => { return function (this: This, ...args: Args): Return { if (param.dataProvider) { const newArgs = (this as any)[param.dataProvider] as Args; return target.call(this, ...newArgs) as Return; } return target.call(this, ...args) as Return; }; }; };
测试类代码:
class SubList { @Test({ dataProvider: "modifiable" }) public testMod(list: number[], from: number, to: number): void { console.log(list, from, to); } public static modifiable: [number[], number, number] = [[1, 2, 3], 4, 5]; } (new SubList()).testMod([], 0, 0); // 报错:newArgs is undefined
解决方案
问题根源是实例this无法直接访问类的静态成员,需要通过实例的constructor属性获取所属类,再访问静态属性。
修改装饰器中返回的包装函数:
return function (this: This, ...args: Args): Return { if (param.dataProvider) { // 通过constructor获取类,访问静态属性 const Class = this.constructor as Record<string, unknown>; const newArgs = Class[param.dataProvider] as Args; return target.call(this, ...newArgs) as Return; } return target.call(this, ...args) as Return; };
修改后,调用(new SubList()).testMod([], 0, 0)时,会自动使用静态属性modifiable的值作为参数,输出[1, 2, 3] 4 5。
如果需要更严格的类型检查,可以给Class添加类型约束,确保它包含指定的静态属性:
// 约束类包含对应静态属性,类型与方法参数匹配 const Class = this.constructor as { [K in typeof param.dataProvider]: Args }; const newArgs = Class[param.dataProvider];
内容的提问来源于stack exchange,提问作者Mike Lischke
相关产品推荐
相关产品推荐

