TypeScript Mixins
A mixin is a code reuse pattern used to mix multiple independent functional modules into a single class.
TypeScript implements mixins by having generic functions return extended classes, making up for the limitation that single inheritance cannot reuse behavior from multiple sources.
Basic concepts
The core of a mixin is a generic function that takes a base class and returns an extended class.Constructor Type constraints are used to describe "any class that can be extended".
Example
// Constructor type: describes any instantiable class
type Constructor
<
T
=
{
}
=
new
(...
args
:
any
[
]
)
=>
T
;
// Mixin function: takes a base class, returns a new extended class
function
Timestamped
<
TBase
extends
Constructor
(
Base:
TBase
)
{
return
class
extends
Base
{
createdAt
=
new
Date
(
)
;
}
;
}
// Base class
class
User
{
constructor
(
public name
:
string
)
{
}
}
// Get a new class after mixing in
const
TimestampedUser
=
Timestamped
(
User
)
;
const
user
=
new
TimestampedUser
(
"Alice"
)
;
console.
log
(
user.
name
)
;
// Alice
console.
log
(
user.
createdAt
instanceof
Date
)
;
// true
Running result:
Alice
true
Note:A mixin does not modify the original class; instead, it returns a completely new extended class, and the original
Userclass is unaffected.
Combining multiple mixins
By nesting multiple mixin functions, multiple capabilities can be stacked onto the same class in sequence.
Example
type Constructor
<
T
=
{
}
=
new
(...
args
:
any
[
]
)
=>
T
;
// Mixin 1: add a timestamp
function
Timestamped
<
TBase
extends
Constructor
(
Base:
TBase
)
{
return
class
extends
Base
{
createdAt
=
new
Date
(
)
;
}
;
}
// Mixin 2: add serialization
function
Serializable
<
TBase
extends
Constructor
(
Base:
TBase
)
{
return
class
extends
Base
{
serialize
(
)
:
string
{
return
JSON.
stringify
(
this
)
;
}
}
;
}
// Mixin 3: add logging (depends on the serialize method)
function
Loggable
<
TBase
extends
Constructor
<
{
serialize
(
):
string
}
(
Base
:
TBase
)
{
return
class
extends
Base
{
log
(
)
:
void
{
console.
log
(
"[LOG]"
,
this
.
serialize
(
)
)
;
}
}
;
}
class
Product
{
constructor
(
public name
:
string
,
public price
:
number
)
{
}
}
// Stack the three mixins in sequence
const
AdvancedProduct
=
Loggable
(
Serializable
(
Timestamped
(
Product
)
)
)
;
const
p
=
new
AdvancedProduct
(
"Phone"
,
999
)
;
p.
log
(
)
;
console.
log
(
p.
createdAt
instanceof
Date
)
;
// true
Running result:
[LOG] {"name":"Phone","price":999,"createdAt":"2026-..."}
true
Combining mixins with interfaces
The class returned by a mixin can declare that it implements an interface, allowing consumers to operate on the mixed-in object through the interface type without depending on the concrete implementation.
Example
type Constructor
<
T
=
{
}
=
new
(...
args
:
any
[
]
)
=>
T
;
// Define a capability interface
interface
ISerializable
{
serialize
(
)
:
string
;
}
interface
ICloneable
<
T
{
clone
(
):
T
;
}
// Mixin implements the interface
function
Serializable
<
TBase
extends
Constructor
(
Base:
TBase
)
{
return
class
extends
Base
implements
ISerializable
{
serialize
(
)
:
string
{
return
JSON.
stringify
(
this
)
;
}
}
;
}
function
Cloneable
<
TBase
extends
Constructor
(
Base:
TBase
)
{
return
class
extends
Base
{
clone
(
)
{
return
Object
.
assign
(
Object
.
create
(
Object
.
getPrototypeOf
(
this
)
)
,
this
)
;
}
}
;
}
class
Article
{
constructor
(
public title
:
string
,
public content
:
string
)
{
}
}
const
RichArticle
=
Cloneable
(
Serializable
(
Article
)
)
;
const
a1
=
new
RichArticle
(
"TypeScript Basics"
,
"Body content..."
)
;
const
a2
=
a1.
clone
(
)
;
a2.
title
=
"Advanced TypeScript"
;
console.
log
(
a1.
serialize
(
)
)
;
// {"title":"TypeScript Basics","content":"Body content..."}
console.
log
(
a2.
serialize
(
)
)
;
// {"title":"Advanced TypeScript","content":"Body content..."}
console.
log
(
a1.
title
===
a2.
title
)
;
// false (independent modification after cloning)
Running result:
{"title":"TypeScript 入门","content":"正文内容..."}
{"title":"TypeScript 进阶","content":"正文内容..."}
false
Mixins with constraints
Through generic constraints, you can restrict a mixin to only mix into classes that meet specific conditions, avoiding missing required properties at runtime.
Example
type Constructor
<
T
=
{
}
=
new
(...
args
:
any
[
]
)
=>
T
;
// Constraint: the base class must have id and name properties
type WithIdAndName
=
Constructor
<
{
id:
number
;
name
:
string
}
;
function
Printable
<
TBase
extends
WithIdAndName
(
Base:
TBase
)
{
return
class
extends
Base
{
(
)
:
void
{
console.
log
(
`
[
$
{
this
.
id
}
]
$
{
this
.
name
}
`
)
;
}
}
;
}
class
Item
{
constructor
(
public id
:
number
,
public name
:
string
)
{
}
}
// Correct: Item satisfies the constraint
const
PrintableItem
=
Printable
(
Item
)
;
const
item
=
new
PrintableItem
(
42
,
"Keyboard"
)
;
item.
(
)
;
// [42] Keyboard
// Incorrect example (the compiler will block it):
// class NoId { constructor(public name: string) {} }
// const Bad = Printable(NoId); // Error: NoId is missing the id property
Running result:
[42] Keyboard
Mixins vs. inheritance
| Dimension | Inheritance (extends) | Mixin |
|---|---|---|
| Number of sources | Can only inherit from one parent class | Can stack any number |
| Degree of coupling | Strong coupling between subclass and parent | Each mixin is independent, with low coupling |
| Granularity of reuse | Reuse the capabilities of an entire class | Reuse a single feature on demand |
| Type Safety | Native support | Requires generic constraints to ensure |
| Applicable scenarios | Strong "is-a" relationship | Cross-cutting concerns (logging, serialization, caching, etc.) |
Summary
- **Core pattern:** a mixin is a generic function that takes a base class and returns an extended class,
Constructoris the standard constraint type - **Capability stacking:** nesting multiple mixin functions combines multiple capabilities into the same class
- **Interface combination:** the class returned by a mixin can implement an interface, so consumers only need to depend on the interface rather than the concrete class
- **Generic constraints:** through constraints
TBaseyou can limit the applicable scope of a mixin and prevent incorrect use at compile time - **Applicable scenarios:** cross-cutting concerns such as logging, serialization, cloning, and timestamps, superior to multi-level inheritance