TypeScript Styleguide
Indexed Objects: Record<K, V> vs Index Signatures
Two ways to define indexed object types in TypeScript. Explore the differences between Record<K, V> utility type and index signature syntax.
82%
Use Record Utility Type
18%
Use Index Signature
Record Utility Type
Using the Record<K, V> utility type to define indexed object properties.
Code Example
example.ts (Record<K, V>)
type UserRoles = Record<'admin' | 'user' | 'guest', Role>;
type ConfigMap = Record<string, string | number>;
interface Config {
settings: Record<string, unknown>;
features: Record<FeatureName, boolean>;
}Key Benefits
- Concise and readable utility type
- Clear what keys and values are
- Works well with union key types
- Easy to understand intent
- Modern TypeScript approach
- Better for complex key types
Statistics
Index Signature
Using index signatures to define dynamically keyed object properties.
Code Example
example.ts (index signature)
interface UserRoles {
[role: string]: Role;
}
type ConfigMap = {
[key: string]: string | number;
};
interface Config {
settings: { [key: string]: unknown };
features: { [key: FeatureName]: boolean };
}Key Benefits
- Classic TypeScript syntax
- Explicitly shows dynamic keys
- More flexible in some contexts
- Works in interfaces and types
- Better for object-like structures
- Clearer when extending properties
Statistics
Additional Insights
More data points to help you make an informed decision for your team.
995
repositories analyzed