In my current project, I am exploring the possibility of using TypeScript/Javascript object destructuring to target only certain properties of an object while preserving the rest of the properties in a separate variable. I am specifically looking for a way to capture all other properties/keys that are not explicitly targeted.
The scenario I'm working on involves extending a class through inheritance while keeping the APIs similar. In the example provided below, I aim to utilize object destructuring for the properties onlyForB
and alsoOnlyForB
, while passing all remaining properties to the config
variable.
class A {
constructor(config) {
this.name = config.name;
// ...
}
}
class B extends A {
constructor({ onlyForB, alsoOnlyForB, ..config }) { // using ...config doesn't work
this.onlyForB = onlyForB;
this.alsoOnlyForB = alsoOnlyForB;
super(config);
}
}
const b = new B({ onlyForB: "B", alsoOnlyForB: "B2", name: "Satoshi", age: 100});
/**
Trying to achieve the following in class B's constructor
onlyForB -> "B"
alsoOnlyForB -> "B2"
config -> { name: "Satoshi", age: 100 }
*/
When attempting to implement this with
{ onlyForB, alsoOnlyForB, ..config }
which is akin to utilizing the spread syntax for object creation, errors arise. The actual use case involves extending a third-party class with numerous "config" properties and working within a TypeScript environment.
Is there a method to accomplish this task without manually removing all the object properties specific to the B
class?
Side Note: To those familiar with Python, I am seeking a solution resembling the functionality of **kwargs
, as seen in
.def __init__(self, onlyForB, alsoOnlyForB, **kwargs)