Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum:

export enum MyCustomEnum {
  Item1 = 'Item 1',
  Item2 = 'Item 2',
  Item3 = 'Item 3',
  Item4 = 'Item 4',
  Item5 = 'Item 5',
}

I am trying to define a type for the following object structure:

const sampleData = {
  data1: {
    Item1: 'Item 1',
    Item2: 'Item 2',
  },
  data2: {
    Item1: 'Item 1',
    Item2: 'Item 2',
    Item3: 'Item 3',
    Item4: 'Item 4',
  },
  data3: {
    Item1: 'Item 1',
    Item2: 'Item 2',
    Item4: 'Item 4',
  },
};

Up until now, I have come up with the following:

type FilteredSelections = {
  [key: string]: Partial<{
    [key in MyCustomEnum]: string
  }>
};

How can I replace the string in [key in MyCustomEnum]: string with the specific value associated with each key?

For instance, if the key is Item1, the corresponding value should be only 'Item 1' and so forth.

In addition, the values (objects with enum keys and values) belonging to the keys (e.g. data1, data2) within sampleData should align with those within the MyCustomEnum enumeration. Not all enum values need to be present (partial), but random key-value pairs beyond the enum key-value combinations should not be allowed. Thank you in advance!

Answer №1

By utilizing the methods outlined in Using Enum as restricted key type in Typescript and Typescript: string literal union type from enum, you can create a mapped type like this:

type FilteredBuyableMethods = {
  [key: string]: Partial<{
    [key in keyof typeof MyEnum]: `${typeof MyEnum[key]}`
  }>
};

Take note that typeof MyEnum[key] is interpreted as (typeof MyEnum)[key].
(online playground)

This approach not only prevents incorrect keys (those not part of the enum), but also ensures that values correspond correctly to their respective keys.

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

The peculiar behavior of Google Maps markers refreshing inconsistently upon bounds adjustment

I recently completed a project involving a restaurant app using Vue and Google Maps. While everything is functional, I have encountered a persistent bug with the markers. When navigating on the map and the bounds change, some markers seem to disappear. Ev ...

Conceal the message "Table does not contain any data" if data exists in the table

This table is populated with data retrieved via JSON. Here is the structure: <table id="tblClaimSearch" class="display responsive nowrap" cellspacing="0" width="100%"> <thead> <tr> <th><input type="checkbox" ...

3D Animation for All Browsers

I'm currently working on creating a small browser-based game and I've been experimenting with animations to get the desired effect. So far, the animation works well in Opera and Edge, although there is a slight cropping issue in Edge. Unfortunat ...

Vue encountering RangeError due to string length inconsistency in specific environments only

My Vue component is currently live in production within a WordPress theme, but I am encountering an error: jquery.min.js:2 Uncaught RangeError: Invalid string length at repeat$1 (vue.js:11398) at generateCodeFrame (vue.js:11380) at vue.js:1146 ...

The misleading A*(A-star) algorithm inaccurately produces faulty routes and ultimately collapses

I am currently working on implementing the A*(A-star) algorithm in react.js, but I am facing a problem. Whenever the startNode (green) or destinationNode (blue) have more than one neighbour or if there is a cycle in the graph, my program crashes. There see ...

Error encountered when attempting to use _id from a different collection due to a duplicate key

In my database, I currently have 2 collections set up. The first one is a 'Users' collection (which is functioning properly), and the other is a 'Rooms' collection (both designed for a chat application). I am looking to ensure that e ...

"Use jQuery to target the first child element within a parent element that has a specific class

Is there a way to choose only the first child of a specific parent class with a certain class for the purpose of clone()? <div class="sector_order"> <div class="line_item_wrapper"> SELECT THIS DIV </div> <div class=" ...

Is there a way to update Checkbox changes within a Datagrid without selecting the entire row?

My Table Cell Checkbox Behavior Issue: Within a table cell, I have a checkbox that changes upon clicking it. However, the change only occurs the first time. Subsequent clicks on the same checkbox do not trigger any change until I click outside the cell. T ...

Component experiencing issues with service or @Input functionality

I have been struggling with importing a service inside a component and encountering an issue where the Input from the service does not render anything in the template. Let's take a look at my entity: export interface PageState { step: string; } e ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Tips for controlling the size of a textarea in jQuery to prevent it from expanding further

How can I prevent the textarea size from increasing in jQuery? I created a demo where the user can only press 8 enters and enter up to 700 characters. However, my logic fails when the user first presses 7 enters and then starts writing text. The text appe ...

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

Troubles with Jest tests are encountered when using ts-jest in an ES2020/ESNEXT TypeScript project

Currently, I am working on a VueJS project that utilizes ViteJS for transpilation, which is functioning properly. However, when Jest testing is involved alongside ts-jest, the following Jest configuration is used: jest.config.ts import { resolve } from &q ...

Retrieving the value of the button with $(this).val() is the only function that newusername performs

My issue arises when trying to send my data to a PHP file; it only sends the value of the <button> or <input type="button">. If I remove the variable definitions, it will only send the data as a string if they are formatted like this: newuser ...

Utilize PHP to transform JSON data into JavaScript

Hello, I am a newcomer to Stackoverflow and I need some assistance. My issue involves converting JSON with PHP to JavaScript. I am using PHP to fetch data from a database and create JSON, which I then want to convert for use in JavaScript as an object (obj ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Sinon experiences delays during an AJAX call

I am working with Mocha Chai and Sinon to test a revealing module pattern and encountering a timeout failure. How can I effectively test a method that assigns variables from an AJAX request? Test.js (function () { 'use strict'; describe(&a ...