typescript / expert
Snippet
Mixin Composition via Abstract Constructor Signature Typing
Abstract constructor signatures (`abstract new (...args: any[]) => T`) allow TypeScript to compose abstract classes dynamically using function mixins. This enables modular object-oriented designs where abstract requirements are inherited across composed class hierarchies.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type AbstractConstructor<T = {}> = abstract new (...args: any[]) => T;function WithTimestamp<TBase extends AbstractConstructor>(Base: TBase) {abstract class Timestamped extends Base {readonly createdAt: Date = new Date();abstract getMetadata(): Record<string, unknown>;}return Timestamped;}abstract class BaseEntity {abstract readonly id: string;}class UserEntity extends WithTimestamp(BaseEntity) {constructor(public readonly id: string, public readonly name: string) {super();}getMetadata() {return { id: this.id, name: this.name };}}
Breakdown
1
type AbstractConstructor<T = {}> = abstract new (...args: any[]) => T;
Declares a generic construct signature compatible with abstract class constructors.
2
function WithTimestamp<TBase extends AbstractConstructor>(Base: TBase)
Defines a higher-order mixin factory parameterized over an abstract base constructor.
3
abstract class Timestamped extends Base
Creates an inline abstract subclass extending the dynamic Base class argument.
4
class UserEntity extends WithTimestamp(BaseEntity)
Instantiates a concrete class extending the abstract class produced by the mixin.