Home > other >  How can I define a type based on a key in Record<K, T> in Typescript?
How can I define a type based on a key in Record<K, T> in Typescript?

Time:10-15

Suppose I want to construct an object type and map the type to the specific key provided in Record<Keys, Type>.

For example, I have a type User which can be one of 3 strings - user, admin or moderator. I want to have a type Stats that has different properties for each.

Doing so with a union type does not result in what I need:

type UserStats = {
  timeOnline: string;
};
type AdminStats = {
  timeAdmining: string;
};
type ModeratorStats = {
  timeModerating: string;
};
type User = 'USER' | 'ADMIN' | 'MODERATOR';

type Stats = Record<User, UserStats | AdminStats | ModeratorStats>;

How can this be achieved?

CodePudding user response:

Do the changes as like bellow mentioned

Replace :

type Stats = Record<User, UserStats | AdminStats | ModeratorStats>;

With :

const Stats : Record<User, UserStats | AdminStats | ModeratorStats>={
      USER:{timeOnline:"User"},
      ADMIN:{timeAdmining:"Admin"},
      MODERATOR:{timeModerating:"Moderator"}
    };
    
    console.log(Stats.ADMIN);

CodePudding user response:

You should do the opposite, i.e. derive User from Stats to avoid repeating yourself:

type UserStats = {
  timeOnline: string;
};
type AdminStats = {
  timeAdmining: string;
};
type ModeratorStats = {
  timeModerating: string;
};

type User = keyof Stats;

type Stats = {
    USER: UserStats;
    ADMIN: AdminStats;
    MODERATOR: ModeratorStats;
};
  • Related