Class Mixins With Constructor Types

Compose behaviors onto classes with mixin functions whose Constructor parameter preserves the base constructor signature and stacks instance types.

TypescriptData Integrity

Code

typescriptsnippet
40 lines
// Mixin(混入)的基础:用构造器签名约束基类
type Constructor<T = object> = new (...args: any[]) => T;

function Timestamped<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    createdAt = new Date('2026-11-14T09:30:00Z');
    stamp(): string {
      return `created at ${this.createdAt.toISOString()}`;
    }
  };
}

function Tagged<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    tags: string[] = [];
    addTag(tag: string): this {
      this.tags.push(tag);
      return this;
    }
  };
}

class BuildLog {
  title: string;
  constructor(title: string) {
    this.title = title;
  }
}

const TaggedTimestampedLog = Tagged(Timestamped(BuildLog));

const log = new TaggedTimestampedLog('weekly deploy').addTag('release').addTag('infra');

console.log(log.title);
console.log(log.stamp());
console.log(log.tags.join(', '));

const typed: InstanceType<typeof TaggedTimestampedLog> = log;
typed.tags.push('audit');
console.log(typed.tags.length);

How it works

The mixin machinery is one type alias and two factory functions. Constructor<T = object> describes a constructable base class; Timestamped and Tagged both take a TBase extends Constructor parameter and return class extends Base with new members bolted on — Timestamped contributes createdAt and stamp(), Tagged contributes tags and addTag().

BuildLog itself stays a plain class with a single title field. The composition line stacks the mixins around it: Tagged(Timestamped(BuildLog)) — Timestamped wraps BuildLog first, then Tagged wraps that result — and TaggedTimestampedLog is the composed constructor. Instances carry every layer at once: log is created as new TaggedTimestampedLog('weekly deploy') and immediately chains .addTag('release').addTag('infra'), after which the file reads log.title, calls log.stamp() and joins log.tags — all with full static types, no any casts. InstanceType<typeof TaggedTimestampedLog> types the typed alias as that same intersection, which is why typed.tags.push('audit') type-checks.

What to watch for

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

Key statements

type Constructor<T = object> = new (...args: any[]) => T;
return `created at ${this.createdAt.toISOString()}`;
return class extends Base {
tags: string[] = [];
addTag(tag: string): this {
this.tags.push(tag);
return this;
}
};

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `Timestamped`, `Tagged` at load time.