Using the Record Utility Type
The Record<Keys, Type>
utility type constructs an object whose properties are Keys
and the property values are Type
.
Example usage⌗
interface User {
id: number,
name: string,
age: number,
}
type UserId = 1 | 2 | 3;
const userData: Record<UserId, User> = {
1: {1, "Steven Seagall", 40},
2: {2, "Tony Stark", 60},
3: {3, "Jason Bourne", 35},
}
console.log(userData.1);
// {1, "Steven Seagall", 40}
This simple example demonstrates a simple usage of the Record
type. However, you can use this type to create even more complicated key value pairs.
Read other posts
No comments yet!