Is it possible to nest enums within enums in TypeScript programming?

enum TYPES {
  CODE = 1,
  TEXT,
  IMAGE,
  VIDEO
}

enum ALL_TYPES {
  CODE = 1,
  TEXT,
  IMAGE,
  VIDEO,
  NONE
}

Is there a way to incorporate the TYPES enum into the ALL_TYPES enum?

Answer №1

As far as I know, there is ongoing consideration for extending enums, but in the meantime, you can utilize const objects instead:

const CATEGORIES = <const>{
  FRUIT: 1,
  VEGETABLE: 2,
  MEAT: 3,
  DAIRY: 4
};

const ALL_CATEGORIES = <const>{ ...CATEGORIES, NONE: 5 };

Various workarounds are also discussed in the aforementioned thread.

If you require type checking for this, note that a numeric enum is essentially treated as a number from a typing perspective:

enum CATEGORIES {
  FRUIT,
  VEGETABLE,
  MEAT,
  DAIRY
}

declare function processItem(name: string, type: string, category: CATEGORIES): any;

processItem('apple', 'fruit', CATEGORIES.FRUIT); // compiles
processItem('apple', 'fruit', 99); // also compiles (?)

If you opt to use an object as recommended above, you can enforce strict type checking by defining a type for all potential values of that object:

const CATEGORIES = <const>{
  FRUIT: 1,
  VEGETABLE: 2,
  MEAT: 3,
  DAIRY: 4
};

type CATEGORY_VALUE = typeof CATEGORIES[keyof typeof CATEGORIES]

declare function assignType(name: string, type: string, categoryValue: CATEGORY_VALUE): any;

assignType('apple', 'fruit', CATEGORIES.FRUIT); // compiles
assignType('apple', 'fruit', 99); // does not compile

Although slightly more verbose, this approach ensures proper type validation.

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

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

The issue with rendering only one DOM element in AngularJS occurs when there are multiple conditions specified within

Recently, I conducted an experiment as part of my project. I utilized the ng-switch AngularJS directive to create a rendering condition. Here is the controller code: app.controller('MainCtrl', function($scope) { $scope.items = ['test1& ...

Error message: "Invalid context validation for CFSELECT tag when utilizing it within a JavaScript function"

When I run CFSELECT normally it works fine, but when I try to include JavaScript inside it, I encounter an error. The normal version works as expected. <tr id='selectionDropdown'> <td >Non-Keyword Traffic:</td> <t ...

"A collection of elements in Typescript that is uniform in type, denoted by

Is it possible to declare an array of type any[] where all elements are of the same type? For example: // Allowed const array1: any[] = [1, 2, 3]; const array2: any[] = ['a', 'b', 'c']; // Not allowed because it contains bot ...

Using app.use in Express/node.js for routing causes the client to experience excessive delays

After setting up the server-side code in app.js, I encountered an issue: console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works. var express = require("expre ...

Receiving a TypeScript error when passing InnerRef on a styled-component forward

When forwarding innerRef to a styled-component like the example below, a type error occurs in typescript: interface MenuProps { isOpen: boolean } const BaseMenu = styled.ul<MenuProps>` padding: 0; /* ... styles ... */ ${({ isOpen }) => ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

How to Include HttpClient in an Angular Service

Looking for a service that utilizes http requests? import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root&a ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Adding a loader to the specific button that has been clicked can be achieved by following these steps:

I am currently in the process of building an e-commerce platform website and I'm looking to implement a feature where users can add products to their cart with just a click of a button. However, before the product is added to the cart, I want to disp ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Why use getElementById(id) to obtain an element in JavaScript when it already exists in the JS?

Recently, I have observed that a reference to an HTML element with an id can be easily accessed in JavaScript by using a variable named after that id (jsbin). What is the reason for this behavior? Why do we need to use getElementById(id) when we could sim ...

Access the web location using jQuery's ajax functionality

I need help figuring out how to post data to my "mail.py" script without knowing the URL link. Both my jQuery AJAX code and JavaScript file are located in RKProjects/scripts_js/contactform.js The Python script I want to connect to is stored in RKProjects ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Significant Google Maps malfunction detected with API V3

Update: Issue resolved, check out my answer below. The scenario: User interacts with a map-image google maps API V3 is loaded using ajax the map is displayed in a dialog window or lightbox What's going on: The map loads and all features are funct ...

Instructions for attaching an event listener to a Threejs Mesh Object with the help of threex dom events

var domEvents = new THREEx.DomEvents(camera, view.domElement); var div = document.createElement( 'div' ); div.setAttribute('data-remove','mesh1'); div.className = 'close-me'; var label = new THREE.CSS2DObje ...