I am searching how to declare a variable where I can store users by birthdate while avoiding using any
let formatedUsers = {} as "TYPE_NEEDED"
for (let i = 0; i < users.length; i ) {
const user= users[i];
if (!formatedUsers[user.birthdate]) formatedUsers[user.birthdate] = [];
formatedUsers[user.birthdate].push(user);
}
In the end I want my variable "formatedUsers" to be like this:
formatedUsers = {
12-02-1996: [user1, user3, user4],
02-04-1998: [user2],
05-08-1999: [user5, user6]
}
CodePudding user response:
The object keys are strings, and the object values are arrays of users, so a relatively simple Record will do it. Assuming you have a reference to the type of user
, you can do:
const formattedUsers: Record<string, User[]> = [];
If you don't have a reference to the user type, you can extract it first.
type User = (typeof users)[number];
CodePudding user response:
In that case, you can use the Record interface.
let formatedUsers: Record<number, User[]> = {0:[]};
You can also initialize the value like that.
CodePudding user response:
This is more accurate since it requires keys to be number-number-number
const formattedUsers: Record<`${number}-${number}-${number}`, User[]> = {};