简体   繁体   English

如何在 typescript 中声明自定义类型的 arrays 的 object

[英]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”是这样的:

formatedUsers = {
12-02-1996: [user1, user3, user4],
02-04-1998: [user2],
05-08-1999: [user5, user6]
}

The object keys are strings, and the object values are arrays of users, so a relatively simple Record will do it. object键是字符串,object值是用户的arrays,所以一个比较简单的Record就可以了。 Assuming you have a reference to the type of user , you can do:假设您有对user类型的引用,您可以执行以下操作:

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

In that case, you can use the Record interface.在这种情况下,您可以使用 Record 接口。

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

You can also initialize the value like that.您也可以像这样初始化值。

This is more accurate since it requires keys to be number-number-number这更准确,因为它要求键是number-number-number

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM