Tips for developing a nested enum in TypeScript

enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

Can a type be defined by extracting the enum from the SystemState object like so?

type stageType -> 1 | 2 (equivalent to the integral values of the Stage enum)

I attempted to use

keyof typeof SystemState['Stage']
, but this resulted in a string union type instead:
"STARTED" | "COMPLETED"
.

Answer №1

One method to try is using the ValueOf function, which maps each key of the enum to its corresponding value and then merges those types together. By incorporating this utility type with your enum, you can generate a union of its values:

enum Stage {
  STARTED = 1,
  COMPLETED
}

const SystemState = {
  Stage,
}

type ValueOf<T> = T[keyof T];

type StageType = ValueOf<typeof SystemState['Stage']>;

Answer №2

Typescript enums can be quite surprising in behavior compared to enums in other programming languages. When transpiled, they may introduce subtle bugs that are not immediately obvious. Check out this informative article discussing the potential pitfalls: https://dev.to/ivanzm123/dont-use-enums-in-typescript-they-are-very-dangerous-57bh

The article also presents an interesting alternative approach to enums using a const object like this:

const Roles = {
  Admin: "admin",
  Writer: "writer",
  Reader: "reader"
} as const;

// Define a type from object keys
type RoleKeys = typeof Roles[keyof typeof Roles]

declare function hasAccess(role: RoleKeys): void;

// This will cause an error
move('guest');

// This is correct!
move('admin');

// Another valid usage
move(Roles.Admin);

I hope you find this information useful!

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 creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Mysterious Source within AngularJS $resource

I have been encountering the error of unknown provider, and have explored various solutions but I feel like there is something missing: app.js var myApp = angular.module('myApp', [ 'ngResource', 'myAppControllers', ...

Successfully connected with status 200, however, an angular promise is triggering an error due to the absence of 'Access-Control-Allow-Origin' header

Initially, I have confirmed that CORS is enabled and functioning in my web API by successfully sending post/get requests from another controller. However, when CORS is disabled, I encounter issues with posting/getting data from the server. The same situati ...

Issue with VueJS not functioning properly upon initial interaction or initial trigger

After some trial and error, I was able to successfully create dynamic elements. The main goal of this exercise is to generate dynamic divs based on a specified "count", with the ability to add multiple textboxes inside each div. If you're curious to ...

A concise way to write an else if statement in Javascript and jQuery

Is there a way to make this code more concise? It works perfectly fine, but it's too lengthy. Basically, the code involves two dropdown lists where the user selects options, and based on their selection, values appear in two textboxes. The catch is th ...

Sending a JSON Object to an API endpoint using the $.ajax method

While attempting to extract data from a form by clicking a button and sending it to a web method in my code behind, I am aiming to pass it as a JSON object, following what seems to be the convention. Below is the current code snippet that I have, but unfor ...

HTML is loaded repeatedly using the ajax load() function, without involving JSON

My idea involves the seamless loading of HTML files from one to another. The visual representation below can provide a better understanding. To illustrate, there are several HTML files - no1.html, no2.html, no3.html, no4.html, etc. - all sharing a common J ...

Is it possible to enlarge a div using "display: table-cell" property when clicked on?

There are various components displayed on my webpage: I require all components to have a minimum height of 150px. If the height is less than 150px, I want to vertically center their text. In case the height exceeds 150px, I aim to truncate the text at 15 ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Three.js - Troubleshooting: Imported OBJ model displaying partially transparent triangles

Currently, I am encountering an issue with an obj file that was exported from Rhino3D into obj format. In this case, half of the triangles making up a certain part of the model appear to be transparent, despite appearing fine in the 3D editor. var loader ...

What is the best method for choosing these elements and surrounding them with a wrapper?

I need to style a title with two radio inputs by wrapping them in a form: <p><strong>Country</strong></p> <div class="radioWrapper"> <span class="label">Canada</span> <span class="radio"> ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Experiencing challenges in redirecting users based on state using React-Router

My application component redirects a user if they are logged in by setting the value to true. I found an online example that worked after trying different methods. If there is a simpler and more functional way to achieve this in React, please let me know. ...

Is it possible to generate a new array by combining the keys of one array object with the values of another array object?

I have a situation with two arrays set up like this arr1 = [ { 'name':'Victoria Cantrell', 'position':'Integer Corporation', 'office':'Croatia', 'ext' ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

JavaScript xPath is ineffective at providing a return value

Trying to work through an issue with xPath and I am new to this concept. Any guidance or assistance in JavaScript would be greatly appreciated. Here is the simple HTML document that I have: <!DOCTYPE html> <html> <head> < ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

The process of executing a PHP file from JavaScript using XMLHttpRequest is experiencing issues on a XAMPP local server

I'm attempting to execute a PHP file using JavaScript. I have my XAMPP server set up and all files saved in the htdocs folder. The PHP file is also stored in the htdocs folder and works correctly when accessed via http://localhost/php_test.php in Chro ...

Converting HTML to PDF with rtl support using the JavaScript library jsPDF

I'm attempting to convert HTML to PDF using jsPDF in an Angular 5 project. Below is the code I have so far: import * as jsPDF from "jspdf"; . . . htmlToPdf(){ var doc=new jsPDF(); var specialElementHandlers = { '#content' : function ...