Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums.

Enum

export enum OverviewSections {
  ALL = 'all',
  SCORE = 'score_breakdown',
  PERFORMANCE = 'performance_over_time',
  ENGAGEMENT = 'engagement',
  COMPANY = 'company_views_graph',
  PEOPLE = 'people_views_graph',
  ARTICLES = 'articles_read_graph',
  PLATFORM = 'platform_sessions_graph',
  EMAILS = 'emails_opened_graph',
}

My goal is to develop a generic type that allows me to structure my data in the following way:

Overview: {
    [OverviewSections.ALL]: {
      data: IOverview | null,
      loading: boolean,
      error: boolean
    },
    [OverviewSections.SCORE]: {
      data: IScore | null,
      loading: boolean,
      error: boolean
    },
    [OverviewSections.PERFORMANCE]: {
      data: IPerformace | null,
      loading: boolean,
      error: boolean
    },
    ......
},

If anyone has any insights or suggestions on how I can accomplish this, I would greatly appreciate it. Thank you!

Answer №1

Here's a useful tip to enhance safety in your code:


// Switching from ENUM to IMMUTABLE object for increased security

const OverviewSections = {
  ALL: 'all',
  SCORE: 'score_breakdown',
  PERFORMANCE: 'performance_over_time',
} as const

// Introducing a type for boilerplate code
type DataStatus<T> = {
  data: T | null
  loading: boolean,
  error: boolean
}

// Mock interfaces to test
interface IOverview {
  tag: 'IOverview'
}
interface IScore {
  tag: 'IScore'
}
interface IPerformance {
  tag: 'IPerformance'
}

// Mapping the types for clarity
type Mapped = {
  [OverviewSections.ALL]: IOverview;
  [OverviewSections.PERFORMANCE]: IPerformance;
  [OverviewSections.SCORE]: IScore
}

// Defining a type that captures all values of OverviewSections
type Values<T> = {
  [P in keyof T]: T[P]
}[keyof T]

/**
 * Main type implementation:
 * 1) Maps through all values of OverviewSections
 * 2) Checks if value matches key in Mapped
 * 3) Creates DataStatus with relevant generic if match is found
 * 4) Returns NEVER if no match is found
 */
type MakeType<E extends Record<string, string>, M> = {
  [P in Values<E>]: P extends keyof M ? DataStatus<M[P]> : never
}

type Result = MakeType<typeof OverviewSections, Mapped>

Remember, you always have the option to revert back to using an enum if needed.

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

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...

What methods are available for altering state in Server Actions in NextJS 13?

Struggling to Implement State Change in NextJS 13 Server Actions I have encountered a challenge with altering state within the execution of server actions in NextJS 13. The scenario involves an actions.ts file located at the root of the app directory. Cur ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Efficiently run multiple Node-written apps on a single server

I currently have a single VPS and would like to host multiple node.js apps on it, similar to how Apache or Nginx works. I am using Nginx as a proxy, but I have concerns. As you know, one of the key features of Node.js is its non-blocking I/O and sing ...

Commencing a New Ember.js Venture

I've recently started using Ember.js and I'm used to simply typing rails project33 to create a new Rails project. But with Ember, it seems like there are multiple steps involved: mkdir project43 && cd project43 npm install -g genera ...

Experience the power of React TypeScript where functions are passed as props, but access is restricted

Currently, I am working on creating a toggle button using react and typescript. In order to challenge myself, I have decided to pass a function as a prop to a child component to implement a complex feature. From what I remember, utilizing 'this.props& ...

Updating the regex pattern for the date format to dd-M-yy in jQuery Validation Engine

Snippet for validating date format using JavaScript: "date": { // Custom function to check if date is valid with leap year consideration "func": function (field) { //var pattern = ne ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Leveraging web workers for asynchronous API calls

Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side: - worker-client.js export const workerFetch = (method = "get", url = "/", data = {}) => new Promise((res ...

Code that achieves the same functionality but does not rely on the

I utilized a tutorial to obtain the ajax code below. The tutorial referenced the library jquery.form.js. Here is the code snippet provided: function onsuccess(response,status){ $("#onsuccessmsg").html(response); alert(response); } $("# ...

Managing cookies with ReactJs: A guide to setting, storing, and updating cookies without deleting the existing ones

How can I create a cookie that stores input values when the user submits a form, and updates the cookie without removing previously saved data on subsequent submissions? export default function saveToCookie() { const [ name, setName ] = useState('&a ...

Tips for managing lag caused by large raw image re-renders in a React application

When trying to change the background position of a user-uploaded background image that is in raw Data URI format using CSS, I noticed that re-rendering becomes slow if the image size exceeds 1mb. This issue does not occur with smaller images. Is there a ...

Exploring Virtual Reality with the Oculus Quest2 and Three.js

Currently, I am working on a project using Oculus and three.js to create a virtual reality experience. To test the functionality, I decided to try out the official sample provided. Here is the link to the official sample. My intention was to access the s ...

Swapping one div for another, all the while incorporating a limited number of buttons within the webpage

I'm faced with a dilemma on my HTML page. In the middle of the content, there's a div that contains 4 links with images and text inside. What I'm looking to achieve is for each link to trigger a complete change in the div when clicked, with ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

How can I resolve the issue of the input field added dynamically by JavaScript not appearing in the PHP $_POST variable?

I have a form nested within an HTML table. Using jQuery, I am dynamically adding input fields to the form. However, when I submit the form and check the $_POST array with var_dump(), the added fields are not showing up. Why is this happening? Below is th ...

How can I retrieve a text file using an API in a Next.js application?

Is there a way to download a text file using an API in Next.js? The console.log(ninjas) function is already displaying the correct information. I have tested the API with Postman and it works perfectly. When I use GET in Postman, the same information is ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...