LoginSignup
0
0

More than 1 year has passed since last update.

TypeScript で Cloneメソッドを実装する(浅いコピー)

Posted at

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);

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0