Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare an object of arrays of custom type in typescript

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]
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading