Mixins
suggest changeA mixin is a function that accepts a base class and returns a derived class. This keeps the resulting members visible to the type system.
type Constructor<T extends object = object> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
readonly createdAt = new Date();
};
}
class Message {
constructor(readonly text: string) {}
}
const TimestampedMessage = Timestamped(Message);
const message = new TimestampedMessage("hello");
void message.createdAt;
Prefer composition for complex behavior; mixins are most useful for small, orthogonal capabilities.
The constructor helper uses any[] deliberately because it must accept and forward arbitrary constructor parameter lists. Keep such uses of any inside small, well-tested type helpers rather than allowing them to spread through application code. Private and protected members can also make mixin constraints harder to compose.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents