Typescript Decorator or Inheritance for additional attributes

Viewed 242

Say I have currently the following model structure,

class Entity {
   id : string;
}

class HateoasEntity extends Entity{
   _links : any;
   _msgs : any;
}

class EditableEntity extends HateoasEntity{
   _new : boolean;
   _editInProgress : boolean
}

class Employee extends EditableEntity{
    name : string;
    address : string;
}

For this, Can I create custom typescript decorators to add those metadata without inheritance?

@Entity
@HateoasEntity
@EditableEntity
class Employee{
  name : string;
  address: string;
}

Is it a good way to go with decorators? Or what i am trying to achieve is bad design?

1 Answers

You can archive the desired behavior using typescript decorators by adding required fields to the class prototype. However you'll lose the main benefit of TypeScript - typing information.

Take a look on the Intersection types:

interface EntityFields {
   id : string;
}

interface HateoasFields {
   _links : any;
   _msgs : any;
}

interface EditableFields {
   _new : boolean;
   _editInProgress : boolean
}

interface EmployeeFields {
    name : string;
    address : string;
}

type Employee = EntityFields & HateoasFields & EditableFields & EmployeeFields

This way you still have typing information and you can easily reuse fields in other places.

Related