Interfaces Extend Classes Reuse Members

Extend a class with an interface to inherit its members, attach extra audit fields, and call inherited methods on the typed instance.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
class Account {
  readonly id: string;
  balance: number;

  constructor(id: string, balance: number) {
    this.id = id;
    this.balance = balance;
  }

  deposit(amount: number): void {
    this.balance += amount;
  }
}

interface AuditableAccount extends Account {
  auditTrail: string[];
}

const audited: AuditableAccount = Object.assign(
  new Account("acct-1", 10),
  { auditTrail: [] },
);

audited.deposit(5);
audited.auditTrail.push("deposit:5");

console.log("id:", audited.id);
console.log("balance:", audited.balance);
console.log("trail:", audited.auditTrail.join(","));
console.log("is account:", audited instanceof Account);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

id: acct-1
balance: 15
trail: deposit:5
is account: true

How it works

Interfaces Extend Classes Reuse Members is built around the class Account.

What to watch for

  • Runs on what the toolchain already provides — nothing beyond it.

Putting it to use

The run emits 3 labeled sections — id:, balance:, trail: — one per step.

Core lines

this.balance += amount;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed.