Typescript Utility Types: Record<Keys, Type>
Utility types are built-in type transformers in TypeScript that help you manipulate and transform existing types into new types. Think of them as type-level functions that take existing types as input and produce new modified types as output.
The
Record
utility type in TypeScript is used to create an object type whose keys are of a specified type and whose values are of another specified type. This utility type is useful for creating objects with specific key-value pairs, such as dictionaries or maps.
Syntax
The Record
utility type is defined as follows:
type Record<Keys extends keyof any, Type> = {
[K in Keys]: Type;
};
The Record
utility type takes two type parameters:
Keys
: The type of the keys in the resulting object type. This type must be a union of string or number literal types, or a string or number literal type.Type
: The type of the values in the resulting object type.
Examples
Example: User permissions type
type Roles = 'admin' | 'user' | 'guest';
type Permissions = Record<Roles, boolean>;
// Equivalent to:
// type Permissions = {
// admin: boolean;
// user: boolean;
// guest: boolean;
// }
// Create a permissions object
const userPermissions: Permissions = {
admin: true,
user: true,
guest: false
};
console.log(userPermissions);
// { admin: true, user: true, guest: false }
Example: Creating a Dictionary
The
Record
utility type can be used to create a dictionary object with specific key-value pairs.
For example, the following code creates a dictionary object where the keys are strings and the values are numbers:
type NumberDictionary = Record<string, number>;
const scores: NumberDictionary = {
alice: 100,
bob: 90,
charlie: 80,
};
console.log(scores.alice); // Output: 100
In this example, the NumberDictionary
type is defined as a dictionary object with string keys and number values. The scores
object is then created using this type, with the keys 'alice'
, 'bob'
, and 'charlie'
and their corresponding values.
Example: Creating a Map
The Record
utility type can also be used to create a map object with specific key-value pairs. For example, the following code creates a map object where the keys are numbers and the values are strings:
type StringMap = Record<number, string>;
const colors: StringMap = {
1: 'red',
2: 'green',
3: 'blue',
};
console.log(colors[1]); // Output: 'red'
In this example, the StringMap
type is defined as a map object with number keys and string values. The colors
object is then created using this type, with the keys 1
, 2
, and 3
and their corresponding values.
Summary
- The
Record
utility type in TypeScript is a powerful tool for creating object types with specific key-value pairs. - By specifying the types of the keys and values, you can create dictionaries, maps, and other objects with precise constraints.