Is there a way to establish a data type using a specific key within the Record<K, T> structure in Typescript?

Imagine the scenario where an object type needs to be created and linked to a specific key specified in Record<Keys, Type>.

Let's say there is a type called User, which can have one of three values - user, admin, or moderator. A new type called Stats needs to be defined with distinct properties for each of these values.

Unfortunately, using a union type does not produce the desired outcome:

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

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

What would be the approach to achieve this goal?

Answer №1

To prevent redundancy, it is recommended to derive User from Stats instead:

type UserProfile = {
  activities: string;
};
type AdminProfile = {
  tasksPerformed: string;
};
type ModeratorProfile = {
  communityEngagement: string;
};

type User = keyof Stats;

type Stats = {
    USER: UserProfile;
    ADMIN: AdminProfile;
    MODERATOR: ModeratorProfile;
};

Answer №2

Make the following modifications:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

Form appears outside the modal window

I am facing an issue with my modal where the form inside is displaying outside of the modal itself. Despite trying to adjust the CSS display settings and switching to react-bootstrap from regular bootstrap, the problem persists. I am uncertain about what s ...

Is it better to set Angular2 @Inputs as public, or should we opt for a stricter API by keeping them private?

I am currently utilizing Angular2 with Typescript Imagine having the following code in the template of my app component: ... <coffee-cup [coffee]="" ... Here is my coffee-cup component: @Component({ selector: 'coffee-cup', ... }) ex ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

Resolving callback definition issue: Can be assigned to constraint, yet may be instantiated with a distinct subtype. ( TS 2345 )

Seeking insight on the typing issue causing a compiler error in the code snippet below. Any suggestions for maintaining type-safety without resorting to any or as? Avoiding these workarounds is important to me. The challenge lies in the evidence() call, c ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Compelled to utilize unfamiliar types in TypeScript generics

When working with a Typescript React form builder, I encountered a situation where each component had different types for the value and onChange properties. To tackle this issue, I decided to utilize generics so that I could define the expected types for e ...

Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some component ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

What is the best way to determine the appropriate generic type for this situation?

Here is an example of some code: type secondaryObjectConstraint = { [key: string]: number } abstract class Base<TObject extends object, TSecondaryObject extends secondaryObjectConstraint> {} type secondaryObjectType = { myProp: number } c ...

Using NodeJS API gateway to transfer image files to S3 storage

I have been attempting to upload an image file to S3 through API Gateway. The process involves a POST method where the body accepts the image file using form-data. I crafted the lambda function in TypeScript utilizing the lambda-multipart-parser. While it ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

What is the best way to add a clickable link/button in Angular 8 that opens a webpage in a new tab?

I'm looking to create a website that opens in a new tab when a link or button is clicked. I'm unsure how to achieve this in Angular 8. ...

Utilizing the namespace importation method correctly

How can I efficiently utilize classes from a namespace that may be the same or different from the current file's namespace? I currently have the following two files. TypeA.ts: export namespace Game { @ccclass export class TypeA extends cc.Component ...

Building a TTL based schema in NestJs with MongooseIn this guide, we will explore

In my NestJs(TypeScript) project, I am attempting to create a self-destructing schema using the mangoose and @nestjs/mongoose libraries. Unfortunately, I have been unable to find a clear way to implement this feature. While I know how to do it in an expres ...

When attempting to select dates from the picker options, the array is found to be devoid of any entries

My challenge lies in working with an array of dates retrieved from the server to determine which dates should be disabled on the datepicker. getStaffAvailability(){ let x = this; this.$http.get(this.weeklyAvailabilityUrl + "GetAv ...

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

Unable to resolve external modules in TypeScript when using node.js

I wanted to integrate moment.js into my node application, so I proceeded by installing it using npm: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc0c2c0c8c3d9ed9f8399839d">[email protected]</a> J ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...