#Class decorator to add properties to class based on type

4 messages · Page 1 of 1 (latest)

worldly mist
#

Say I have the following interface...

interface Person {
    name: string;
    age: number;
}
```ts

and I have a class that uses the interface like this...
```ts
abstract class GenericForm<T> {
    abstract validators: { [P in keyof T]: [T[P], ValidatorFn?] };
}

class PersonForm extends GenericForm<Partial<Person>> {
   readonly validators = {};

   constructor(readonly model: Partial<Person>) {
      // ...
   }
}

is it possible to create a decorator that will modify the PersonForm class to look like this?

@someDecorator(Person)
class PersonForm extends GenericForm<Partial<Person>> {
   readonly validators = {};

   // "injected" by @someDecorator
   readonly name = this.get("name") as FormControl; // assume this.get is valid here. I am doing stuff with angular forms and omitted the part where i extend FormGroup for brevity.
   readonly age = this.get("age") as FormControl;  
   // end "injections"  

   constructor(readonly model: Partial<Person>) {
      // ...
   }
}
#

sorry I think my "example" i tried to write is a little confusing so here is my actual implementation:

export interface Schedule {
    id: number;
    int_miles: number;
    term_miles: number;
    term_months: number;
    // ...
}

export class ScheduleForm extends FormGroup {
    // I want to "inject" the creation of these properties via some class decorator that reads the Schedule interface.
    readonly id = this.get("id") as FormControl;
    readonly int_miles = this.get("int_miles") as FormControl;
    // --------------------

    constructor(readonly model: Partial<Schedule>, readonly fb = new FormBuilder()) {
        super(fb.group({
            id: [model?.id],
            int_miles: [model?.int_miles, [Validators.required]],
            // ...
        }).controls);
    }
}
untold haven
#

using function components rather than class components would be my suggestion since it would remove most of the reason you seem to be wanting to do this code gen with decorators in the first place

untold haven
#

here's an example