I'm in the process of developing a custom decorator that adds a specific property to the target class.
Here is my current implementation for the decorator:
export type Constructable<T> = new (...args: any[]) => T;
export function ValidationSchema() {
return <BaseClass extends Constructable<{}>>(target: BaseClass) =>
class extends target {
constructor(...args: any[]) {
super(...args);
}
validate() {
console.log(this);
}
};
}
When applying this decorator to a class as shown below:
@ValidationSchema()
export class Test {
public foo: string;
}
Everything seems to be functioning correctly. However, when attempting to call the validate
method on an instance of the class, I encounter an error indicating that the property does not exist on the type. To work around this issue, I have used // @ts-ignore
, which successfully resolves the problem.
Is there a way for TypeScript to identify that an instance of the Test
class (or any other class decorated with the same decorator) should inherit the type of the anonymous class generated by the decorator?
I have referred to a similar GitHub issue and discussions related to Mixin classes. Despite reviewing these resources, I am unsure how to implement them within my decorator approach. Is it feasible to achieve this using decorators or would a factory function be more appropriate?
Thank you in advance for any insights or recommendations!