Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
}
like image 932
Mor Bargig Avatar asked Jan 20 '26 08:01

Mor Bargig


2 Answers

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 ^^

like image 76
vic1707 Avatar answered Jan 22 '26 21:01

vic1707


Here is one way to do it:

class Parent {
  propertyToKeep = 'hi';
  propertyToDelete = 'bye';
  constructor() {}
}

class Child extends Parent {
  constructor() {
    super();
    delete this.propertyToDelete;
  }
}

const myObject = new Child();

console.log(myObject);
/* OUTPUT:
  {
    "propertyToKeep": "hi"
  }
*/
like image 28
Eduardo Veras Avatar answered Jan 22 '26 23:01

Eduardo Veras