TypeScript Conditional Types
Conditional types are one of the most powerful features of the TypeScript type system.
They allow types to be selected dynamically based on conditions, similar to the ternary expression in programming languages.
Conditional types make type definitions more flexible and are the foundation for implementing advanced utility types.
Why conditional types are needed
In real TypeScript development, we often need to return different types based on different input types.
For example, a function may accept a string or a number, and we need to return different result types depending on the parameter type.
Conditional types provide the ability to make logical decisions at the type level, making type definitions more flexible and powerful.
Concept explanation:The syntax of a conditional type is
T extends U ? X : Y. If type T is assignable to type U, return type X; otherwise return type Y.
Basic Syntax
Conditional types use the syntax of a ternary expression to make conditional decisions at the type level.
This allows us to compute return types dynamically based on input types.
Example
// Conditional type syntax: T extends U ? X : Y
// If T is a string type, return true; otherwise return false
type IsString
<
T
=
T
extends
string
?
true:
false
;
// Use a conditional type
// string extends string is true, so type A is true
type A
=
IsString
<
string
;
// number extends string is false, so type B is false
type B
=
IsString
<
number
;
// Use these types
var
a
:
A
=
true
;
var
b
:
B
=
false
;
console.
log
(
"Is string a string?: "
a
)
;
console.
log
(
"Is number a string?: "
b
)
;
Running result:
string 是字符串?: true
number 是字符串?: false
Explanation:Conditional types are evaluated automatically during type checking, producing concrete types.
Practical application: type filtering
One of the most common uses of conditional types is filtering types.
For example, you can create a type that excludes null and undefined.
Example
// Implement NonNullable with a conditional type
// If T is null or undefined, return never (the empty type); otherwise return T itself
type NonNullable
<
T
=
T
extends
null
|
undefined
?
never:
T
;
// Use the NonNullable type
// string is not null/undefined, so the type is string
type A
=
NonNullable
<
string
;
// null is null/undefined, so the type is never
type B
=
NonNullable
<
null
;
// undefined is null/undefined, so the type is never
type C
=
NonNullable
<
undefined
;
// Verify the types
var
a
:
A
=
"hello"
;
console.
log
(
"Non-null: "
a
)
;
Running result:
非空: hello
The never type:never represents a type that never exists. When a condition is not met, TypeScript uses never to represent an "unavailable" type.
Type inference: the infer keyword
The infer keyword is one of the most powerful features of conditional types.
It allows you to "extract" or "infer" specific parts from a type.
Example
// Use infer to infer a function's return type
// If T is a function type, return the inferred return type R; otherwise return never
type ReturnType
<
T
=
T
extends
(...
args
:
any
[
]
)
=>
infer R
?
R
:
never
;
// Define a function that returns a user object
function
getUser
(
)
{
return
{
name
:
"Alice"
}
;
}
// Define a function that returns a number
function
getNumber
(
)
{
return
42
;
}
// Use ReturnType to get a function's return type
// Inferred as { name: string }
type R1
=
ReturnType
<
typeof
getUser;
// Inferred as number
type R2
=
ReturnType
<
typeof
getNumber;
// Use the inferred types
var
r1
:
R1
=
{
name
:
"Bob"
}
;
var
r2
:
R2
=
100
;
console.
log
(
"User: "
JSON.
stringify
(
r1
)
)
;
console.
log
(
"Number: "
r2
)
;
Running result:
用户: {"name":"Bob"}
数字: 100
The role of infer:infer is like a "variable" in the type system; it can capture a specific part of a type and use it in the resulting type.
Distributive conditional types
When the generic parameter of a conditional type is a union type, distribution happens automatically.
That is, the condition is applied to each member of the union separately and the results are then merged.
Example
// ToArray converts type T into an array type
// When T is a union type, each type is distributed automatically
type ToArray
<
T
=
T
extends
any
?
T
[
]:
never
;
// The union type is distributed automatically
// string | number is distributed as: ToArray
// That is: string[] | number[]
type StrOrNum
=
ToArray
<
string
|
number;
// You can assign string[] or number[]
var
arr
:
StrOrNum
=
[
"hello"
]
;
// You can also assign number
arr
=
42
;
console.
log
(
"Array: "
arr
)
;
Running result:
数组: 42
The distribution mechanism:The distributive behavior of conditional types is enabled by default. To disable distribution, use square brackets:
[T] extends U。
Combining conditional types with mapped types
Conditional types can be combined with mapped types to create powerful type transformation tools.
This combination is the foundation of TypeScript's built-in utility types.
Example
// Define a user interface
interface
User
{
// The user ID
id
:
number
;
// Username
name
:
string
;
// User email
:
string
;
}
// Implement Partial with mapped and conditional types
// Iterate over all properties of T and add the optional modifier ?
type Partial
<
T
=
{
[
P
inkeyof T
]
?:
T
[
P
]
;
}
;
// Implement Required with mapped and conditional types
// Iterate over all properties of T and remove the optional modifier -?
type Required
<
T
=
{
[
P
inkeyof T
]
-?:
T
[
P
]
;
}
;
// Use Partial: all properties become optional
var
partial
:
Partial
<
User
=
{
name:
"Alice"
}
;
// Use Required: make the properties of Partial
// Partial must exist first
type RequiredUser
=
Required
<
Partial
<
User;
var
required
:
RequiredUser
=
{
name
:
"Bob"
,
id
:
1
}
;
console.
log
(
"Optional: "
JSON.
stringify
(
partial
)
)
;
console.
log
(
"Required: "
JSON.
stringify
(
required
)
)
;
Running result:
可选: {"name":"Alice"}
必填: {"name":"Bob","id":1}
Using them together:Combining conditional and mapped types can implement various complex type transformations, such as the built-in utility types Partial, Required, and Readonly.
Advanced example: type checking
Conditional types can also be used to implement more complex type checks.
Here are some type-checking examples useful in real development.
Example
// Check whether a type is any
// any intersected with any type yields any, so 0 extends any is true
type IsAny
<
T
=
0
extends
(
1
&
T
)
?
true:
false
;
// Test IsAny
// any is a special type that yields any when intersected with any type
type A
=
IsAny
<
any
;
// true
// string is not any
type B
=
IsAny
<
string
;
// false
console.
log
(
"Is any any?: "
A
)
;
console.
log
(
"Is string any?: "
B
)
;
// Check whether a type is assignable
// If T is assignable to U, return true; otherwise return false
type IsAssignableTo
<
T
,
U
=
T
extends
U
?
true:
false
;
// Test type assignability
// string is assignable to any, so return true
type CanAssign
=
IsAssignableTo
<
string
,
any;
console.
log
(
"Is string assignable to any?: "
CanAssign
)
;
Running result:
any 是 any?: true
string 是 any?: true
Note:any is the most "permissive" type in TypeScript; it can be assigned to any type and can accept assignments from any type.
Notes
- **Deferred evaluation:** Conditional types are evaluated lazily, computed only when a concrete type is used
- **Distribution:** Union types automatically trigger the distribution mechanism of conditional types
- **infer can only be used in extends conditions:** This is the only place infer can appear
- **Combined with mapped types:** Conditional types combined with mapped types can create powerful utility types
Advanced:Many TypeScript built-in utility types (such as Partial, Required, and Extract) are implemented with conditional types.
Summary
Conditional types are one of the most powerful features of the TypeScript type system.
- Basic syntax:
T extends U ? X : Y - **infer keyword:** Infer specific parts from a type
- **Distribution:** Union types are distributed automatically
- **Use cases:** Type filtering, type inference, and type checking
- **Utility types:** Most built-in utility types are implemented with conditional types
Best practices:Mastering conditional types lets you write more flexible and type-safe code.