TypeScript Index Types and the keyof Keyword
Index types and keyof are powerful tools for working with object types in TypeScript.
They allow us to dynamically access object properties and create flexible type mappings.
Why index types are needed
In JavaScript, we often need to access object properties dynamically.
For example, a function may need to get all the keys of an object, or access the corresponding value type by a key.
Index types and keyof let us express this dynamism in the type system while maintaining type safety.
Concept:Index types are types that allow dynamic access to object properties, while keyof is used to obtain a union type of all the keys of an object type.
The keyof operator
The keyof operator is used to obtain a union type of all the keys of an object type.
Example
// Define the user type
interface
User
{
id
:
number
;
// User ID
name
:
string
;
// Username
:
string
;
age
?:
number
;
// Age (optional)
}
// Use keyof to get the union type of all keys
// Result: "id" | "name" | "email" | "age"
type UserKeys
=
keyof User
;
// Test keyof
function
getProperty
<
T
,
K
extendskeyof T
(
obj
:
T
,
key
:
K
)
:
T
[
K
]
{
return
obj
[
key
]
;
}
const
user
:
User
=
{
id
:
1
,
name
:
"Alice"
,
:
"alice@example.com"
}
;
// Get the name property
const
userName
:
string
=
getProperty
(
user
,
"name"
)
;
console.
log
(
"Username: "
userName
)
;
Running result:
用户名: Alice
Explanation:keyof returns a literal union type of the key names, not a string type.
Indexed access types
Using indexed access types (Index Access Type), you can obtain the type of an object property.
Example
// Define the user type
interface
User
{
id
:
number
;
name
:
string
;
:
string
;
}
// Use indexed access types to get a property's type
type UserId
=
User
[
"id"
]
;
// number
type UserName
=
User
[
"name"
]
;
// string
// You can use a union type to access multiple keys
type UserIdAndName
=
User
[
"id"
|
"name"
]
;
// number | string
// Use keyof to get a union of all property types
type AllUserValues
=
User
[
keyof User
]
;
// number | string
// Practical usage example
function
getValue
<
T
,
K
extendskeyof T
(
obj
:
T
,
key
:
K
)
:
T
[
K
]
{
return
obj
[
key
]
;
}
const
user
:
User
=
{
id
:
1
,
name
:
"Bob"
,
:
"bob@test.com"
}
;
// Get the id type
const
idValue
:
number
=
getValue
(
user
,
"id"
)
;
console.
log
(
"ID: "
idValue
)
;
// Get the name type
const
nameValue
:
string
=
getValue
(
user
,
"name"
)
;
console.
log
(
"Name: "
nameValue
)
;
Indexed access:Using square brackets [] accesses the specific property type of an object type, which is very powerful and flexible.
Mapped type basics
Mapped types allow creating new types based on existing ones by iterating over all their keys.
Example
// Define the user type
interface
User
{
id
:
number
;
name
:
string
;
:
string
;
age
:
number
;
}
// Make all properties optional
type PartialUser
=
Partial
<
User
;
// Make all properties readonly
type ReadonlyUser
=
Readonly
<
User
;
// Custom mapped type: make all properties optional and stringify them
type Stringify
<
T
=
{
[
P
inkeyof T
]
:
string
;
}
;
type StringifiedUser
=
Stringify
<
User
;
// Practical usage example
const
partialUser
:
PartialUser
=
{
id
:
1
,
name
:
"Alice"
// email and age are optional
}
;
const
readonlyUser
:
ReadonlyUser
=
{
id
:
1
,
name
:
"Bob"
,
:
"bob@test.com"
,
age
:
25
}
;
// readonlyUser.name = "Charlie"; // Error: readonly
console.
log
(
"Partial user: "
partialUser.
name
)
;
console.
log
(
"Readonly user: "
readonlyUser.
name
)
;
Mapped types:Using the [P in keyof T] syntax to iterate over all keys of a type is the basis for creating utility types.
Constraining key types
Use keyof and generic constraints to restrict the keys a function accepts.
Example
// Define the config type
interface
Config
{
apiUrl
:
string
;
timeout
:
number
;
retry
:
boolean
;
}
// Only existing keys can be retrieved
function
getConfigValue
<
T
,
K
extendskeyof T
(
config
:
T
,
key
:
K
)
:
T
[
K
]
{
return
config
[
key
]
;
}
// Define the config
const
config
:
Config
=
{
apiUrl
:
"https://api.example.com"
,
timeout
:
5000
,
retry
:
true
}
;
// Correct: key exists
const
url
:
string
=
getConfigValue
(
config
,
"apiUrl"
)
;
const
timeoutVal
:
number
=
getConfigValue
(
config
,
"timeout"
)
;
// Error: key does not exist (TypeScript will report an error)
// const invalid = getConfigValue(config, "unknown");
console.
log
(
"API URL: "
url
)
;
console.
log
(
"Timeout: "
timeoutVal
)
;
Constraints:K extends keyof T ensures that the passed key is one that exists on the object, preventing runtime errors.
Get only properties of a specific type
Extract property keys of a specific type from an object type.
Example
// Define a mixed type
interface
Mixed
{
id
:
number
;
name
:
string
;
age
:
number
;
:
string
;
active
:
boolean
;
}
// Extract all keys of string type
type StringKeys
<
T
=
{
[
K
inkeyof T
]
:
T
[
K
]
extends
string
?
K
:
never
;
}
[
keyof T
]
;
// Extract all keys of number type
type NumberKeys
<
T
=
{
[
K
inkeyof T
]
:
T
[
K
]
extends
number
?
K
:
never
;
}
[
keyof T
]
;
// Test
type StringProps
=
StringKeys
<
Mixed
;
// "name" | "email"
type NumberProps
=
NumberKeys
<
Mixed
;
// "id" | "age"
// Practical application: get the value of a string property
function
getStringProps
<
T
,
K
extends
StringKeys
<
T
(
obj:
T
,
keys
:
K
[
]
)
:
T
[
K
]
[
]
{
return
keys.
map
(
key
=>
obj
[
key
]
)
;
}
const
mixed
:
Mixed
=
{
id
:
1
,
name
:
"Alice"
,
age
:
25
,
:
"alice@test.com"
,
active
:
true
}
;
const
strings
=
getStringProps
(
mixed
,
[
"name"
,
"email"
]
)
;
console.
log
(
"String property: "
strings.
join
(
", "
)
)
;
Conditional types:By combining conditional types and mapped types, you can achieve complex type filtering and extraction.
Iterating over array types
Use indexed types to work with arrays and tuples.
Example
// Define a tuple type
type Tuple
=
[
string
,
number
,
boolean
]
;
// Get the tuple element type
type First
=
Tuple
[
0
]
;
// string
type Second
=
Tuple
[
1
]
;
// number
type Third
=
Tuple
[
2
]
;
// boolean
// Use number to get all element types
type AllElements
=
Tuple
[
number
]
;
// string | number | boolean
// Get the array element type
type StringArray
=
string
[
]
;
type ArrayElement
=
StringArray
[
number
]
;
// string
// Practical application: function overloading
function
getElement
<
T
extends
any
[
]
(
arr:
T
,
index
:
number
)
:
T
[
indexof T
]
|
undefined
{
return
index
<
arr.
length
?
arr
[
index
]
:
undefined
;
}
const
tuple
:
Tuple
=
[
"hello"
,
123
,
true
]
;
const
arr
:
string
[
]
=
[
"a"
,
"b"
,
"c"
]
;
console.
log
(
"Tuple element[0]: "
getElement
(
tuple
,
0
)
)
;
console.
log
(
"Array element[1]: "
getElement
(
arr
,
1
)
)
;
Tuple indexing:Tuples can use numeric indexes, where each index corresponds to a specific element type—something arrays cannot do.
Notes
- **keyof returns a union type:** keyof returns a literal union type of the key names
- **Safe indexed access:** ensure the accessed key exists in the target type
- **Generic constraints:** use extends keyof to constrain generic parameters
- **Mapped types require the in keyword:** mapped types use the [P in keyof T] syntax
Best practices:Indexed types are the cornerstone of creating reusable utility types; mastering them can greatly improve your type-manipulation skills.
Summary
Indexed types and keyof are important parts of the TypeScript type system.
- **keyof:** get all keys of an object type
- **Indexed access:** get a property type by key
- **Mapped types:** create new types based on existing types
- **Type safety:** ensure type safety for dynamic property access
Note:When you need to work with object properties, prefer indexed types to maintain type safety.