1

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

3 Answers 3

4

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];
Sign up to request clarification or add additional context in comments.

5 Comments

date should also be typed, not just string.
Thank you it works, how can I change your answer to accept Date instead of string if I need to?
Object keys cannot be dates. Object keys may only be strings, numbers, or Symbols. If you want to have a Date object as a "key", use a Map instead. Map<Date, User[]>
could there be any checking on date string such as 12-02-1996?
@ABOS Only if the date string is manually constructed - see this other answer for how to type it - but that's likely to require a decent amount of additional code for no real type benefit IMO
0

In that case, you can use the Record interface.

let formatedUsers: Record<number, User[]> = {0:[]};

You can also initialize the value like that.

Comments

0

This is more accurate since it requires keys to be number-number-number

const formattedUsers: Record<`${number}-${number}-${number}`, User[]> = {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.