TypeScriptでCloneメソッドを実装しようとしたら、手こずってしまったので備忘録で書き残しておきます
// Shallow clone example
interface Constructor<M> {
new (...args: unknown[]): M;
}
class Bear {
/** born on */
public readonly bornOn: Date;
constructor(params: { bornOn: Date }) {
this.bornOn = params.bornOn;
}
public clone() {
const constructor = this.constructor as Constructor<this>;
return new constructor(this);
}
}
class PetBear extends Bear {
/** name */
public readonly name: string;
constructor(params: { bornOn: Date; name: string }) {
super(params);
this.name = params.name;
}
}
const bear = new Bear({ bornOn: new Date("1858-10-27") });
const pooh = new PetBear({
bornOn: new Date("1921-08-21"),
name: "Red shirt Pooh",
});
const clonedBear = bear.clone(); // const clonedBear: Bear
const clonedPooh = pooh.clone(); // const clonedPooh: PetBear
console.log(clonedBear);
console.log(clonedPooh);