Upon the release of TypeScript 5.0, the new decorator APIs have been introduced and I am eager to utilize them for automatically providing parameters to a method from a static property within the same class. The decorator parameters and factory are defined as follows:
type TargetFunction<This, Args extends unknown[], Return> = (this: This, ...args: Args) => Return;
class Throwable extends Error {} // For demonstration purposes.
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;
};
};
};
To apply this factory, it can be used in a test class like so:
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); // error, newArgs is undefined
In the playground, it appears that while the code is functional, accessing the static property in the class mentioned as a factory parameter is not possible. What modifications are required to rectify this issue?
The use of the this
parameter does not provide access to the static method. Attempts such as
this.prototype[param.dataProvider]
have also resulted in errors.