Constructor Overloads Accept Multiple Shapes

Give a class several constructor signatures over one implementation so call sites stay typed whether they pass raw parts or a parsed record.

TypescriptData Integrity

Code

typescriptsnippet
29 lines
type LedgerRow = { id: string; cents: number; paid?: boolean };

class Invoice {
  readonly id: string;
  readonly cents: number;
  paid: boolean;

  // Overload 1: raw parts
  constructor(id: string, cents: number, paid?: boolean);
  // Overload 2: an already-parsed record
  constructor(row: LedgerRow);
  // Implementation signature is invisible to callers
  constructor(idOrRow: string | LedgerRow, cents?: number, paid?: boolean) {
    if (typeof idOrRow === 'string') {
      this.id = idOrRow;
      this.cents = cents ?? 0;
      this.paid = paid ?? false;
    } else {
      this.id = idOrRow.id;
      this.cents = idOrRow.cents;
      this.paid = idOrRow.paid ?? false;
    }
  }
}

const fromParts = new Invoice('inv-1', 4950, false);
const fromRow = new Invoice({ id: 'inv-2', cents: 1250, paid: true });
console.log(fromParts.id, fromParts.cents, fromParts.paid);
console.log(fromRow.id, fromRow.cents, fromRow.paid);

Output

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

inv-1 4950 false
inv-2 1250 true

The flow at a glance

Constructor Overloads Accept Multiple Shapes is built around the class Invoice.

Demo state sits in top-level bindings: fromParts, fromRow.

Points of care

  • No dependencies section needed; the standard library is the whole story.

Core statements

this.paid = idOrRow.paid ?? false;
this.paid = paid ?? false;
this.cents = cents ?? 0;

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `fromParts`, `fromRow`.