Implementing a mapping process is inevitable unless you want to manually iterate over object keys, which would make the code harder to read and longer. In such cases, utilizing creational patterning can be more efficient!
class MyTypeOne {
constructor(
public one = '',
public two = '') { }
}
class MyTypeTwo extends MyTypeOne {
constructor(
one = '',
two = '',
public three = '') {
super(one, two)
}
static fromMyTypeOne(myTypeOne: MyTypeOne) {
return new MyTypeTwo(myTypeOne.one, myTypeOne.two);
}
}
const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);
console.log(two);
Auto-Map
For thoroughness, here is an extended version that automatically maps the members. It offers a different set of trade-offs!
class MyTypeOne {
constructor(
public one = '',
public two = '') { }
}
class MyTypeTwo extends MyTypeOne {
constructor(
one = '',
two = '',
public three = '') {
super(one, two)
}
static fromMyTypeOne(myTypeOne: MyTypeOne) {
const typeTwo = new MyTypeTwo();
for (let key in myTypeOne) {
if (myTypeOne.hasOwnProperty(key)) {
typeTwo[key] = myTypeOne[key];
}
}
return typeTwo;
}
}
const one = new MyTypeOne('a', 'b');
const two = MyTypeTwo.fromMyTypeOne(one);
console.log(two);