Home > Software engineering >  TypeScritp Type a generic structure in a JSON
TypeScritp Type a generic structure in a JSON

Time:09-21

I have a JSON like this:

{ users: {
  "username": {"name": "text","last_name": "other text"},
  "username2": {"name": "text","last_name": "other text"},
  "username3": {"name": "text","last_name": "other text"}
  ...
}

And I want to type this as generic, something like this:

  type UserInfo = {name:string, last_name:string}

 type user<T> = {
   T: UserInfo
} 
 type users = {
   users: user<string>
 }

I'm trying to use the generic of user as the key for the object, so I don't have to define a key for username, username2, etc and to make it extensible to "n" username. but it is not working

CodePudding user response:

The mistake in your approach is

 type UserInfo = {name:string, last_name:string}

 type user<T> = {
  // you cannot use type T as a key which needs to be a value
  //(that value can be either string or number as key)
   T: UserInfo     //this is incorrect
} 
 type users = {
   users: user<string>
 }

Having mentioned that, you can use in-built "Record" type for your goal.

type UserInfo = {
  name: string;
  last_name: string;
};

type Users = Record<string, UserInfo>;

// this will suffice, if you want the key to be just string and need not follow any pattern like if its just username or username1.

const users: Users = {
  username: { name: "asdsa", last_name: "asdsa" },
  anyNameOfTheUser: { name: "asdsa", last_name: "asdsadd" },
};

CodePudding user response:

I guess the easy way will by typed as Record like:


type UserInfo = {name:string, last_name:string}

 type users = {
   Record<string,UserInfo>
 }

  • Related