TypeScript Mapped Types
Mapped types are a powerful feature in TypeScript for creating new types based on existing ones.
They allow developers to modify the properties of a type in bulk, such as making all properties optional or making all properties read-only.
Mapped types are the core technique behind TypeScript's built-in utility types.
Why Mapped Types Are Needed
In real TypeScript development, we often need to create variants based on existing types.
For example, you may need a version with all properties optional, or a version with all properties read-only.
The traditional approach is to define these types manually, which is tedious and error-prone.
Mapped types provide a declarative way to generate these type variants automatically.
Concept explanation:Mapped types use the
keyofandinkeyword to iterate over all keys of an existing type, then apply the same type transformation to each key.
Basic mapped types
Basic mapped types create a new type by iterating over all keys of the original type.
This is the basis for implementing utility types such as Partial and Readonly.
Example
// Define a user interface
interface
User
{
// The user ID
id
:
number
;
// Username
name
:
string
;
// User email
:
string
;
}
// Implement the Partial utility type
// Iterate over all keys of T and add the optional modifier ?
type Partial
<
T
=
{// P iterates over all keys returned by keyof T
// T[P] gets the value type for the corresponding key in the original type
[
P
in
keyof T
]
?:
T
[
P
]
;
}
;
// Use the Partial type
type PartialUser
=
Partial
<
User
;
// The PartialUser type is equivalent to:
// { id?: number; name?: string; email?: string }
// You can provide only some of the properties
var
user
:
PartialUser
=
{
name
:
"Alice"
}
;
console.
log
(
"Partial user: "
JSON.
stringify
(
user
)
)
;
Running result:
部分用户: {"name":"Alice"}
Syntax explanation:
[P in keyof T]means iterating over all keys of type T.?modifier makes a property optional.
Property modifiers
Mapped types support several property modifiers to change the characteristics of properties.
These modifiers can be combined to achieve different type transformation needs.
Example
// Define a user interface
interface
User
{
// Username
name
:
string
;
// User age
age
:
number
;
}
// Use readonly mapping: make all properties read-only
// Add the readonly modifier
type Readonly
<
T
=
{
readonly
[
P
inkeyof T
]
:
T
[
P
]
;
}
;
// Use optional mapping: make all properties optional (basic version)
type Optional
<
T
=
{
[
P
inkeyof T
]
?:
T
[
P
]
;
}
;
// Use -? mapping: remove the optional modifier (make required)
// -? removes the existing ? modifier
type Required
<
T
=
{
[
P
inkeyof T
]
-?:
T
[
P
]
;
}
;
// Test the read-only type
var
readonlyUser
:
Readonly
<
User
=
{
name:
"Alice"
,
age
:
25
}
;
// readonlyUser.age = 30; // error: read-only properties cannot be modified
// Test the optional type
var
optionalUser
:
Optional
<
User
=
{
name:
"Bob"
}
;
console.
log
(
"Readonly: "
JSON.
stringify
(
readonlyUser
)
)
;
console.
log
(
"Optional: "
JSON.
stringify
(
optionalUser
)
)
;
Running result:
只读: {"name":"Alice","age":25}
可选: {"name":"Bob"}
Modifier descriptions:
?add optional,-?remove optional;readonlyadd read-only,-readonlyremove read-only.
Key remapping
Mapped types can also use the as keyword to remap key names.
This is very useful when you need to change the format of key names uniformly.
Example
// Define a user interface
interface
User
{
// The user ID
id
:
number
;
// Username
name
:
string
;
// User age
age
:
number
;
}
// Use the as keyword to remap key names
// Add a prefix to all keys
type WithPrefix
<
T
,
Prefix
extends
string
=
{// Use template literal types to rename keys
// Capitalize uppercases the first letter
[
P
in
keyof T as `$
{
Prefix
}
$
{
Capitalize
<
string
&
P
}
`
]:
T
[
P
]
;
}
;
// Use WithPrefix to add a "user" prefix
type PrefixedUser
=
WithPrefix
<
User
,
"user";
// The converted type:
// { userId: number; userName: string; userAge: number }
// Use the type with prefixes
var
user
:
PrefixedUser
=
{
userId
:
1
,
userName
:
"Alice"
,
userAge
:
25
}
;
console.
log
(
"With prefix: "
JSON.
stringify
(
user
)
)
;
Running result:
带前缀: {"userId":1,"userName":"Alice","userAge":25}
Template literal types:Use
`${Prefix}${Capitalizecan dynamically generate new key names.}`
Key filtering
By combining conditional types and mapped types, you can filter keys.
This is very useful when implementing utility types such as Omit.
Example
// Define a user interface
interface
User
{
// The user ID
id
:
number
;
// Username
name
:
string
;
// User password
password
:
string
;
// User email
:
string
;
}
// Implement Omit: exclude specified keys
// Use conditional types to filter keys
type Omit
<
T
,
K
extendskeyof T
=
{
// P iterates over all keys of T
// If P is assignable to K (that is, in the exclusion list), return never (not included)
// Otherwise, return P (keep this key)
[
P
in
keyof T as P
extends
K
?
never
:
P
]
:
T
[
P
]
;
}
;
// Use Omit to exclude the password key
type UserWithoutPassword
=
Omit
<
User
,
"password";
// The converted type:
// { id: number; name: string; email: string }
// Use the type after excluding password
var
user
:
UserWithoutPassword
=
{
id
:
1
,
name
:
"Alice"
,
:
"a@b.com"
}
;
console.
log
(
"No password: "
JSON.
stringify
(
user
)
)
;
Running result:
无密码: {"id":1,"name":"Alice","email":"a@b.com"}
The never type:When never is used as a property type in a mapped type, that property is completely removed.
Conditional mapping
Mapped types can be combined with conditional types to apply different transformations based on the property type.
This makes type conversion more flexible and intelligent.
Example
// Define the API response interfaces
interface
APIResponse
{
// Response data
data
:
string
;
// Error message
error
:
string
;
// Whether it is loading
isLoading
:
boolean
;
// Timestamp
timestamp
:
number
;
}
// Convert function types to () => void
// Iterate over all properties and conditionally transform based on property type
type FunctionToVoid
<
T
=
{// If T[P] is a function type, convert to () => void
// Otherwise, keep the original type unchanged
[
P
in
keyof T
]
:
T
[
P
]
extends
(
...
args
:
any
[
]
)
=>
any
?
(
)
=>
void
:
T
[
P
]
;
}
;
// Use conditional mapping
var
response
:
FunctionToVoid
<
APIResponse
=
{
data:
"hello"
,
error
:
""
,
isLoading
:
false
,
timestamp
:
Date
.
now
(
)
}
;
console.
log
(
"Response: "
JSON.
stringify
(
response
)
)
;
Running result:
响应: {"data":"hello","error":"","isLoading":false,"timestamp":...}
Application scenarios:Conditional mapping is often used in scenarios that require different handling based on type, such as processing API responses and cleaning up configuration objects.
Built-in mapped types
TypeScript includes many utility types implemented based on mapped types.
These utility types can meet most everyday development needs.
Example
// Partial - make all properties optional
type P1
=
Partial
<
{
a:
string
;
b
:
number
}
;
// Result: { a?: string; b?: number }
// Required - make all optional properties required
type R1
=
Required
<
{
a?:
string
;
b
?:
number
}
;
// Result: { a: string; b: number }
// Readonly - make all properties readonly
type RO1
=
Readonly
<
{
a:
string
;
b
:
number
}
;
// Result: { readonly a: string; readonly b: number }
// Pick - select specified properties
type PK
=
Pick
<
{
a:
string
;
b
:
number
;
c
:
boolean
}
,
"a"
|
"b"
;
// Result: { a: string; b: number }
// Omit - exclude specified properties
type OM
=
Omit
<
{
a:
string
;
b
:
number
;
c
:
boolean
}
,
"c"
;
// Result: { a: string; b: number }
// Test Partial
console.
log
(
"Partial: "
JSON.
stringify
(
{
}
as P1
)
)
;
// Test Pick
console.
log
(
"Pick: "
JSON.
stringify
(
{
a
:
"x"
}
as PK
)
)
;
Utility type combinations:These built-in utility types are all implemented based on mapped types and conditional types. Understanding their principles allows better use of them.
Notes
- **keyof keyword:** used to obtain the union type composed of all keys of a type
- **in keyword:** used to iterate over a union of key names
- Modifier position:
?andreadonlyBefore the property name, it means adding a modifier - Minus modifier:
-?and-readonlyused to remove a modifier - **as keyword:** used to remap keys, must return a string or numeric literal type
Advanced:Mapped types can be combined with conditional types and template literal types to achieve complex type transformations.
Summary
Mapped types are one of the most powerful features in the TypeScript type system.
- **keyof:** get all keys of a type
- **in:** iterate over key names for mapping
- **
?:** add optional modifier - **readonly:** add readonly modifier
- **-?:** remove optional modifier
- **as:** remap key names
Best practices:Making good use of mapped types can greatly reduce repetitive type definitions and improve code maintainability.