javascriptangulartypescriptclassoop

i want to extend from one class but delete some property


I have some class for crud API service class I want to extend it but spear few properties for exam this is my class

class Parent {
  public propertyToKeep: any;
  public propertyToDelete: any;
  constructor() { }
}

this is the child class

class Child extends Parent {
  constructor() {
    super();
  }
}

Another file where I don't want to see and get access to

export class comeComponent {
  constructor(private child: Child) {
    this.child.propertyToKeep // work
    this.child.propertyToDelete // error and I can't even see it
  }
}

Solution

  • I just came across the same use case as you and here's how I did it:

    const Omit = <T, K extends keyof T>(Class: new () => T, keys: K[]): new () => Omit<T, typeof keys[number]> => Class;
    

    Then you can use it like so :

    class Child extends Omit(Parent, ['propertyToDelete']) {}
    

    As you can see child only has one property now (it also works with methods).

    The package from @nestjs/swagger has some nice helpers if you're dealing with a NestJS API. Their implementation is more complex so I guess they are keeping other stuff like their own property decorators (I am pretty new to Typescript so maybe I miss the point of all they are doing).

    P.S: French guy tried to answer for first time with imperfect English so please be kind ^^