structuredClone Loses Class Prototypes

structuredClone copies data by structure: the generic result still claims T, but class methods and prototypes are gone unless you reattach them.

TypescriptData Integrity

Code

typescriptsnippet
27 lines
class Invoice {
  number: string;
  paidCents: number;
  constructor(number: string, paidCents = 0) {
    this.number = number;
    this.paidCents = paidCents;
  }
  total(): number {
    return this.paidCents;
  }
}

const original = new Invoice("INV-1", 4900);
console.log(`original total: ${original.total()}`);

// structuredClone 按结构复制:类型参数声称 T,原型与方法不会跟着走
const cloned = structuredClone(original);
console.log(`cloned data: ${cloned.number} ${cloned.paidCents}`);
console.log(`cloned.total is function: ${typeof cloned.total}`);

const revived = Object.assign(Object.create(Invoice.prototype), cloned);
console.log(`revived total: ${revived.total()}`);

// 普通数据(数组/日期/Map)克隆是安全的
const withDate = structuredClone({ due: new Date("2026-03-01T00:00:00Z"), tags: ["net-30"] });
console.log(`due: ${withDate.due.toISOString()}, tags: ${withDate.tags.join(",")}`);

What the snippet does

The moving parts are the class Invoice.

The demo data lives in module-level bindings: original, cloned, revived, withDate.

What to watch for

  • The runtime is the only requirement — no packages, no install.

Applying it

The printed lines stage the lesson in order — original total: 4900, cloned data: INV-1 4900, cloned.total is function: undefined — and then revived total: 4900 shows Object.create(Invoice.prototype) restoring the method.

Statements that matter

const withDate = structuredClone({ due: new Date("2026-03-01T00:00:00Z"), tags: ["net-30"] });
const cloned = structuredClone(original);

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `original`, `cloned`, `revived`.