Mixins: add behaviour to any class
A function that takes a class and returns a subclass, typed with a constructor type. A free TypeScript lesson with examples.
More on Mixins
Keep learning
Overview
createdAt: Date touch(): void isActive: boolean activate(): void tags: string[] tag(t: string): void name: string Mixins to apply member on u comes from new SmartUser(…) still takes User's constructor arguments: (name: string). Each mixin is one more subclass layer. chapters · mixins Mixins: add behaviour to any class
1. The problem: one parent per class
Users, coupons and reviews all need a created date and an on/off switch. But in JavaScript a class can extends (inherit from) only one class. two parents Classes can only extend a single class. JavaScript gives each class exactly one parent, so a comma list after extends is a syntax error. The usual workaround is copy-paste into every class. has name, isActive, activate, createdAt, touch Read line 5 inside out: Activatable(User) makes a User subclass with the switch. Timestamped(…) wraps that in one more subclass with the date.
2. The constructor type
A mixin needs to say "any class". That is a type with a new signature: a description of “something you can call with new, and what it builds”.
the one helper every mixin uses
callable with new, gives a T any constructor arguments (a rest parameter: collects all arguments into one array) a class whose instances have name The rest parameter must be exactly any[]. With unknown[] (“arguments of some type you must check”) the compiler refuses. This is a fixed rule TypeScript has for mixins, not something you can reason out. A mixin class must have a constructor with a single rest parameter of type 'any[]'. In plain words: when you write class extends Base and Base is a type parameter, TypeScript needs Base's constructor to accept ...args: any[]. Here it is unknown[], so the rule fails on line 3.
3. Writing a mixin
any class class extends Base anonymous subclass + fields, methods the new behaviour a new class value The generic TBase is what keeps Base's own members and constructor in the result type.
4. Lab: stack mixins on User
Toggle mixins and watch the instance type grow.
Timestamped(Activatable(User))
Activatable returns Timestamped returns instance type Timestamped-class & Activatable-class & User typeof User is the type of the class itself (its constructor), not of one user. A & B is an intersection: “must match both A and B”. Because typeof User stays in the intersection, its constructor arguments are still checked. The mixins accept any[]. What happens with 42? compiles: mixins take any[] error: number is not assignable to string u is any Step 1: the mixin part says new (...args: any[]), so 42 fits there. Step 2: the result is an intersection with typeof User, so new must also fit User's constructor (name: string). Step 3: 42 is a number, and a number doesn't fit into string. Real message: Argument of type 'number' is not assignable to parameter of type 'string'.
6. Using the mixed class
Timestamped… & Activatable… & User InstanceType<typeof SmartUser> means “the type of an object that new SmartUser(…) returns”. Use it to type a parameter like u above. One mixin works on User, Coupon, Review. Real subclasses instanceof User is still true. Noisy types Hovers show long anonymous class names.
Remember
Make the mixin generic in TBase so the base members survive. Stack them: Timestamped(Activatable(User)). Constructor arguments of the base are still checked. Use InstanceType<typeof Mixed> to name the instance type. ! Cheat code → Go deeper: constrained mixins and composition, classes, InstanceType and friends, decorators.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.