Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below:

enum EventType {
  JOB,
  JOB_EXECUTION,
  JOB_GROUP
}

Now, I am in need of creating an interface structure like this:

interface EventConfigurations {
  JOB: {
    Enabled?: boolean;
  };

  JOB_EXECUTION: {
    Enabled?: boolean;
  };

  JOB_GROUP: {
    Enabled?: boolean;
  };
}

Since there is a direct mapping between the two, I am curious if there is a way to automatically generate the interface based on the enum instead of hardcoding it manually. Any suggestions or insights are greatly appreciated!

Answer №1

To define it as a type (instead of an interface), follow this syntax:

type EventConfigurations = Record<keyof typeof EventType, { Enabled?: boolean }>

Here is the breakdown:

  • When using typeof with an enum, you get a type with string members as keys and numbers as values.
  • Applying keyof to that type results in a union type containing each key.
  • The Record<K, V> construct maps type K to type V.

Playground Link

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

What is the use of the typeof operator for arrays of objects in TypeScript?

How can I update the any with the shape of the options's object below? interface selectComponentProps { options: { label: string; value: string; }[]; } const SelectComponent: React.FC<selectComponentProps> = ({ options, }) => ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

Tips for adapting the position of a floating div according to its height and environment

Important Note: The code below utilizes the rubuxa plugin for handling JS sortables. Javascript: function querySelector(expr){return document.querySelector(expr)} var container = querySelector('.ITEST'); var sortable = Sortable.create(container, ...

Utilize the csv-parser module to exclusively extract the headers from a file

Recently, I've been exploring the NPM package csv-parser which is designed to parse CSV files into JSON format. The example provided demonstrates how you can read a CSV file row by row using the following code snippet: fs.createReadStream('data.c ...

Guide to making a button in jQuery that triggers a function with arguments

I've been working on creating a button in jQuery with an onClick event that calls a function and passes some parameters. Here's what I have tried so far: let userArray = []; userArray['recipient_name'] = recipient_name.value; userArray[ ...

Using JavaScript to auto-scroll a textarea to a certain position

Is there a way to change the cursor position in a textarea using JavaScript and automatically scroll the textarea so that the cursor is visible? I am currently using elem.selectionStart and elem.selectionEnd to move the cursor, but when it goes out of view ...

Discovering the destination link of a website while utilizing GM_xmlhttpRequest

Picture yourself browsing a webpage called "www.yourWebsite.com" and utilizing userscripts in Tampermonkey to extract data from another site using the GM_xmlhttpRequest function. As you make requests with the GM_xmlhttpRequest function to visit "exampleWe ...

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Guide on implementing "Displaying 1 of N Records" using the dataTables.js framework

let userTable = $("#user_table").DataTable({ 'sDom': '<"row-drop"<"col-sm-12 row"lr>><"row"t><"row-pager"<"col-sm-12 col-md-5"i><"col-sm-12&qu ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Is there a way to remove the initial number entered on a calculator's display in order to prevent the second number from being added onto the first one?

I am currently in the process of developing a calculator using HTML, CSS, and JavaScript. However, I have encountered an issue with my code. After a user inputs a number and then clicks on an operator, the operator remains highlighted until the user inputs ...

Unexpectedly, the Discord bot abruptly disconnects without any apparent cause

Hey there! I've encountered an issue with my Discord bot - it keeps disconnecting after a few hours without any apparent cause! This particular bot is designed to regularly ping the Apex Legends game servers to check their status and display the ser ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...

What is the comparable javascript code for the <script src="something1.json"></script> tag?

Within my HTML code, I currently have the following line to read a JSON file: <script src="something1.json"></script> Inside this JSON file, there is a structure like so: var varName = { .... } This method of definition naturally sets up ...

Creating an HTML list based on a hierarchical MySQL table structure

I have retrieved a hierarchical table showing different elements and their parent-child relationships as follows: id| name | parent_id | header 1 | Assets | 0 | Y 2 | Fixed Assets | 1 | Y 3 | Asset One | 2 | N 4 | ...

Using styled-components and typescript to override props

Currently, I am faced with the challenge of using a component that necessitates a specific property to be set. My goal is to style this component with the required property already defined, without having to manually specify it again during rendering. Howe ...