TypeScript infer Keyword
infer is a keyword in TypeScript conditional types, used to infer a new type from an existing type.
It allows extracting and deriving types within generic conditional types, enabling powerful type manipulation.
Why the infer keyword is needed
In generic programming, we often need to extract part of a type from a complex type.
For example, from Promise extract string, from Array extract User。
The infer keyword makes this kind of type extraction elegant and type-safe: it can declare a type variable in a conditional type and then use it in the true branch.
Concept explanation:infer is short for "infer", meaning "to infer". It can only be used in the extends clause of a conditional type, to declare a type variable to be inferred.
Basic Usage
Use infer in a conditional type to infer a type.
Example
// Extract the value type from a Promise
// If T is a Promise
type ValueOf
<
T
=
T
extends
Promise
<infer V
?
V
:
never
;
// Test
type Str
=
ValueOf
<
Promise
<
string;
// string
type Num
=
ValueOf
<
Promise
<
number;
// number
type NotPrm
=
ValueOf
<
string
;
// never
// Usage example
var
promise
:
Promise
<
string
=Promise.
resolve
(
"hello"
)
;
var
value
:
ValueOf
<
typeof
promise
=
"world";
console.
log
(
"String extraction: "
(
typeof
value
===
"string"
?
"Success"
:
"Failed"
)
)
;
Running result:
字符串提取: 成功
Explanation:
infer VA type variable V is declared, and TypeScript infers V's type automatically.
Extract the array element type
Extract the element type from an array type.
Example
// Extract the element type of an array
// If T is an array V[], return V
type ArrayElement
<
T
=
T
extends
(infer V
)
[
]
?
V
:
never
;
// Test
type User
=
{
name
:
string
}
;
type Users
=
User
[
]
;
type E1
=
ArrayElement
<
string
[
];
// string
type E2
=
ArrayElement
<
Users
;
// User
type E3
=
ArrayElement
<
number
;
// never (not an array)
// Usage example
var
users
:
Users
=
[
{
name
:
"Alice"
}
]
;
var
element
:
ArrayElement
<
Users
=
users
[
0
];
console.
log
(
"Element type: "
element.
name
)
;
Applications:This pattern is often used to extract elements of a specific type from a union type.
Extract the function return type
Extract the return type from a function type.
Example
// Extract the return type of a function
type ReturnType
<
T
=
T
extends
(...
args
:
any
[
]
)
=>
infer R
?
R
:
any
;
// Test
function
getData
(
)
{
return
{
id
:
1
,
name
:
"Alice"
}
;
}
function
fetchUser
(
id
:
number
)
:
Promise
<
User
{
returnPromise.
resolve
(
{
id
,
name
:
"Bob"
}
)
;
}
type R1
=
ReturnType
<
typeof
getData;
// { id: number; name: string }
type R2
=
ReturnType
<
typeof
fetchUser;
// Promise
// Usage example
var
result
:
R1
=
{
id
:
1
,
name
:
"Test"
}
;
console.
log
(
"Return type: "
JSON.
stringify
(
result
)
)
;
Built-in types:TypeScript's built-in
ReturnTypeutility types are implemented using infer.
Extract function parameter types
Extract parameter types from a function type.
< h2 class="example">Example
// Extract the first parameter type of a function
type FirstParameter
<
T
=
T
extends
(
first:
infer P
,
...
rest
:
any
[
]
)
=>
any
?
P
:
never
;
// Test
function
createUser
(
name
:
string
,
age
:
number
)
:
User
{
return
{
id
:
1
,
name
}
;
}
function
logMessage
(
msg
:
string
)
:
void
{
console.
log
(
msg
)
;
}
type P1
=
FirstParameter
<
typeof
createUser;
// string
type P2
=
FirstParameter
<
typeof
logMessage;
// string
type P3
=
FirstParameter
<
(
)
=>
void;
// never
// Usage example
var
nameParam
:
P1
=
"Alice"
;
console.
log
(
"Parameter type: "
nameParam
)
;
Note:You can use the
...rest: any[]to match any number of remaining parameters.
Multiple infer
Use multiple infer statements in a single conditional type.
Example
// Extract the first two element types of a tuple
type FirstTwo
<
T
=
T
extends
[infer A
,
infer B
,
...
rest
:
any
[
]
]
?
[
A
,
B
]
:
never
;
// Test
type Tuple
=
[
string
,
number
,
boolean
]
;
type FirstTwoTypes
=
FirstTwo
<
Tuple
;
// [string, number]
// Extract object properties
type ObjectValue
<
T
=
T
extends
{
value:
infer V
}
?
V
:
never
;
type WithValue
=
{
value
:
string
;
name
:
string
}
;
type ExtractedValue
=
ObjectValue
<
WithValue
;
// string
// Usage example
var
tupleResult
:
FirstTwoTypes
=
[
"hello"
,
123
]
;
console.
log
(
"Tuple: "
JSON.
stringify
(
tupleResult
)
)
;
Tuple:Use
...rest: any[]can match the remaining elements of a tuple.
Using infer in recursive types
Use infer in recursive type utilities to implement complex type operations.
Example
// Deep readonly type - recursively apply infer
type DeepReadonly
<
T
=
T
extends
Function
?
T:
T
extends
object
?
{
readonly
[
P
in
keyof T
]
:
DeepReadonly
<
T
[
P
]
}:
T
;
// Test
interface
User
{
name
:
string
;
address
:
{
city
:
string
;
zip
:
string
;
}
;
}
type ReadonlyUser
=
DeepReadonly
<
User
;
// Flatten Promise types
type FlattenPromise
<
T
=
T
extends
Promise
<infer U
?
U
extends
Promise
<
any
?
FlattenPromise
<
U:
U
:
T
;
type Nested
=
Promise
<
Promise
<
string;
type Flat
=
FlattenPromise
<
Nested
;
// string
// Usage example
var
user
:
ReadonlyUser
=
{
name
:
"Alice"
,
address
:
{
city
:
"Beijing"
,
zip
:
"100000"
}
}
;
// user.name = "Bob"; // Error: readonly
console.
log
(
"Deep readonly: "
user.
name
)
;
Recursive infer:Using infer in recursive types enables deep type transformations, such as deep readonly and deep optional.
Notes
- **Only usable on the right side of extends:** infer can only be used in the extends clause of a conditional type
- **Declare a type variable:** use
infer Vto declare a type variable to be inferred - **Multiple uses:** more than one infer can be used in a single conditional type
- **Inference failure returns never:** if inference fails, the conditional type returns never
Best practices:infer is the core of implementing custom utility types; mastering it enables powerful type operations.
Summary
infer is one of the most powerful features in the TypeScript type system.
- **Type extraction:** extract part of a type from a complex type
- **Conditional inference:** infer types within conditional types
- **Function-related:** extract function parameters and return types
- **Recursive utilities:** implement deep type transformations
Note:A deep understanding of infer lets you write more advanced type utilities, improving type safety and development efficiency.