TypeScript Intersection Types
Intersection types combine multiple types into one new type, which contains all the members of the constituent types.
This is similar to multiple inheritance in object-oriented programming, allowing one type to have the characteristics of multiple types.
Why intersection types are needed
In development, a type often needs to have the characteristics of multiple types.
For example, an employee is both a person (Person) and a worker (Worker), needing the attributes of both.
Intersection types let us combine multiple types into one, satisfying this need.
Concept explanation:Using intersection types
&The symbol connects multiple types, indicating that the new type contains all members of those types. This is similar to the concept of multiple inheritance.
Basic Syntax
Use & Use the symbol to combine multiple types.
Example
// Define the person type
// Contains name and age
interface
Person
{
name
:
string
;
age
:
number
;
}
// Define the worker type
// Contains company name and salary
interface
Worker
{
company
:
string
;
salary
:
number
;
}
// Use an intersection type to merge two interfaces
// The Employee type has all properties of both Person and Worker
type Employee
=
Person
&
Worker
;
// Create an object with the characteristics of both types
var
employee
:
Employee
=
{
name
:
"Alice"
,
age
:
25
,
company
:
"Google"
,
salary
:
100000
}
;
console.
log
(
"Employee: "
JSON.
stringify
(
employee
)
)
;
Running result:
员工: {"name":"Alice","age":25,"company":"Google","salary":100000}
Explanation:Intersection type
A & Bmeans the new type has all properties of both A and B, none can be missing.
Intersection types vs. interface inheritance
Intersection types can replace multiple inheritance of interfaces.
Example
// Define type A
interface
A
{
a
:
string
;
}
// Define type B
interface
B
{
b
:
number
;
}
// Use an interface to inherit multiple interfaces
// Use extends to inherit multiple interfaces
interface
AB
extends
A
,
B
{
c
:
boolean
;
}
// Use an intersection type (more concise)
// Directly use the & symbol to combine types
type ABType
=
A
&
B
&
{
c
:
boolean
}
;
// Both approaches create a type containing all properties
var
obj
:
ABType
=
{
a
:
"hello"
,
b
:
42
,
c
:
true
}
;
console.
log
(
"Object: "
JSON.
stringify
(
obj
)
)
;
Running result:
对象: {"a":"hello","b":42,"c":true}
Comparison:Intersection types are more concise than interface inheritance, especially when inheriting multiple types and adding extra properties.
Type mixing (Mixin pattern)
Using intersection types to implement the Mixin pattern allows dynamically combining class functionality.
Example
// Define a constructor function type
// Accept any arguments and return an object
type Constructor
=
new
(
...
args
:
any
[
]
)
=>
{
}
;
// Mixin: add timestamp functionality
// Return a new class that extends Base
function
Timestamped
<
T
extends
Constructor
(
Base:
T
)
{
return
class
extends
Base
{
timestamp
=
Date
.
now
(
)
;
}
;
}
// Mixin: add serialization functionality
// Return a new class that extends Base and includes a serialize method
function
Serializable
<
T
extends
Constructor
(
Base:
T
)
{
return
class
extends
Base
{
serialize
(
)
{
return
JSON.
stringify
(
this
)
;
}
}
;
}
// Base user class
class
User
{
name
:
string
;
constructor
(
name
:
string
)
{
this
.
name
=
name
;
}
}
// Combine mixins
// Create a user class with timestamp functionality
var
TimestampedUser
=
Timestamped
(
User
)
;
// Create a user class with serialization functionality
var
SerializableUser
=
Serializable
(
User
)
;
// Combine two mixins
var
FullUser
=
Serializable
(
Timestamped
(
User
)
)
;
// Create an instance and test
var
user
=
new
FullUser
(
"Alice"
)
;
console.
log
(
// 6. Get timestamp
user.
timestamp
)
;
console.
log
(
"Serialization: "
user.
serialize
(
)
)
;
Running result:
时间戳: 17134...
序列化: {"name":"Alice","timestamp":17134...}
Mixin pattern:This is a powerful pattern that adds new functionality to a class without modifying the original class.
Intersection types and union types
When combining intersection and union types, pay special attention to precedence.
Example
// Union type: can be a string or a number
type StringOrNumber
=
string
|
number
;
// Intersection type: intersection of incompatible types
// string & number = never (no type is both a string and a number)
type Both
=
string
&
number
;
// Define three types
type A
=
{
a
:
string
}
;
type B
=
{
b
:
number
}
;
type C
=
{
c
:
boolean
}
;
// Combine union and intersection types
// (A | B) & C intersects each branch of the union with C
type Combined
=
(
A
|
B
)
&
C
;
// The actual result is: { a: string; c: boolean } | { b: number; c: boolean }
// That is, either A + C or B + C
var
obj
:
Combined
=
{
a
:
"hello"
,
c
:
true
}
;
console.
log
(
"Combination: "
JSON.
stringify
(
obj
)
)
;
Running result:
组合: {"a":"hello","c":true}
Important:Intersecting incompatible types yields
nevertype. For examplestring & numberis invalid.
Practical intersection types
Intersection types are often used to create utility types and achieve type transformations.
Example
// Mapped type: make all properties optional
// Iterate over all properties of T, adding ? to make them optional
type Partial
<
T
=
{
[
P
inkeyof T
]
?:
T
[
P
]
}
;
// Mapped type: make all properties required
// Iterate over all properties of T, removing ? to make them required
type Required
<
T
=
{
[
P
inkeyof T
]
-?:
T
[
P
]
}
;
// Mapped type: make all properties readonly
// Iterate over all properties of T, adding readonly
type Readonly
<
T
=
{
readonly
[
P
inkeyof T
]
:
T
[
P
]
}
;
// Define a configuration interface
interface
Config
{
host
:
string
;
port
:
number
;
}
// Use the utility types
var
partialConfig
:
Partial
<
Config
=
{
host:
"localhost"
}
;
var
requiredConfig
:
Required
<
Config
=
{
host:
"localhost"
,
port
:
8080
}
;
var
readonlyConfig
:
Readonly
<
Config
=
{
host:
"localhost"
,
port
:
8080
}
;
console.
log
(
"Partial: "
JSON.
stringify
(
partialConfig
)
)
;
console.
log
(
"Required: "
JSON.
stringify
(
requiredConfig
)
)
;
console.
log
(
"Readonly: "
JSON.
stringify
(
readonlyConfig
)
)
;
Running result:
部分: {"host":"localhost"}
必填: {"host":"localhost","port":8080}
只读: {"host":"localhost","port":8080}
Utility types:The TypeScript standard library provides many utility types based on intersection and mapped types, such as Partial, Required, and Readonly.
Notes
- **Incompatible types:** intersecting incompatible types yields never
- **Precedence:** union types have higher precedence than intersection types
- **Method conflicts:** if two types have methods with the same name, you must handle the conflict manually
Best practices:Intersection types are suitable for combining multiple interfaces or types; when multiple inheritance is needed, prefer intersection types over interface inheritance.
Summary
Intersection types are a powerful type-composition tool in TypeScript.
- **Syntax:** use
&the symbol to connect multiple types - **Merge:** the new type contains all members of the types
- **Mixin:** can be used to implement class functionality composition
- **never:** intersecting incompatible types yields the never type
Note:Using intersection types wisely can create flexible type combinations, but be careful to avoid unnecessary intersections that result in the never type.