Retrieving data from Typescript enums using strings

I need assistance extracting values from this enum:

enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}

Although I followed recommendations from other sources, the output I am receiving is unexpected. Here is what I currently get:

var text=""
for (var size in Sizes) {
    text = text + "\n" + size;
}

console.log(text);

Tiny
VerySmall
Very Large
Small
Medium
Large
VeryLarge

I specifically do not want to include VerySmall and VeryLarge in my results. Can anyone explain why these are showing up and how I can achieve my desired outcome?

Appreciate any help provided.

Answer №1

It seems like the typescript compiler being used is version pre-2.4, where string value support was not yet added in enums. Typically, there's a reverse mapping from values to enums and values are usually numbers. However, if you tried to use strings before version 2.4, the compiler wouldn't know how to handle it (and would actually result in errors), but it would still generate the source code.

Contrast with version 2.4:

var Sizes;
(function (Sizes) {
    Sizes["Tiny"] = "Tiny";
    Sizes["VerySmall"] = "Very Small";
    Sizes["Small"] = "Small";
    Sizes["Medium"] = "Medium";
    Sizes["Large"] = "Large";
    Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));

Versus version 2.3:

var Sizes;
(function (Sizes) {
    Sizes[Sizes["Tiny"] = "Tiny"] = "Tiny";
    Sizes[Sizes["VerySmall"] = "Very Small"] = "VerySmall";
    Sizes[Sizes["Small"] = "Small"] = "Small";
    Sizes[Sizes["Medium"] = "Medium"] = "Medium";
    Sizes[Sizes["Large"] = "Large"] = "Large";
    Sizes[Sizes["VeryLarge"] = "Very Large"] = "VeryLarge";
})(Sizes || (Sizes = {}));

And version 2.3 without string values:

var Sizes;
(function (Sizes) {
    Sizes[Sizes["Tiny"] = 0] = "Tiny";
    Sizes[Sizes["VerySmall"] = 1] = "VerySmall";
    Sizes[Sizes["Small"] = 2] = "Small";
    Sizes[Sizes["Medium"] = 3] = "Medium";
    Sizes[Sizes["Large"] = 4] = "Large";
    Sizes[Sizes["VeryLarge"] = 5] = "VeryLarge";
})(Sizes || (Sizes = {}));

If you wish to enforce that reverse mapping in versions 2.4 and higher, you can assert the values to any.

enum Sizes {
  Tiny = <any>"Tiny",
  VerySmall = <any>"Very Small",
  Small = <any>"Small",
  Medium = <any>"Medium",
  Large = <any>"Large",
  VeryLarge = <any>"Very Large"
}

We'll just consider it a feature.

Answer №2

To retrieve the enum keys and display their values, you can utilize Object.keys in the following manner:

enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}

for (const size of Object.keys(Sizes)) {
    console.log(Sizes[size]);
}

Result:

Tiny
Very Small
Small
Medium
Large
Very Large

Code after transpilation:

var Sizes;
(function (Sizes) {
    Sizes["Tiny"] = "Tiny";
    Sizes["VerySmall"] = "Very Small";
    Sizes["Small"] = "Small";
    Sizes["Medium"] = "Medium";
    Sizes["Large"] = "Large";
    Sizes["VeryLarge"] = "Very Large";
})(Sizes || (Sizes = {}));
for (var _i = 0, _a = Object.keys(Sizes); _i < _a.length; _i++) {
    var size = _a[_i];
    console.log(Sizes[size]);
}

Answer №3

In my TypeScript example


enum Sizes {
  Tiny = "Tiny",
  VerySmall = "Very Small",
  Small = "Small",
  Medium = "Medium",
  Large = "Large",
  VeryLarge = "Very Large"
}
class SizePrinter {
  constructor() {
    let text = '';

    for (const key in Sizes) {
      if (Sizes.hasOwnProperty(key)) {
        text += Sizes[key] + '<br/>';
      }
    }
    console.log(text);

    text = '';
    Object.keys(Sizes).map(key => text += Sizes[key] + '<br/>');
    console.log(text);
  }
}
let printer = new SizePrinter();

It's important to include an if-statement within a for-In loop!

Both console.log(text) statements should display the same output string.

Tiny<br/>Very Small<br/>Small<br/>Medium<br/>Large<br/>Very Large<br/>

If you log Sizes[size] to the console after the for-In loop, you can understand what happens and why you get the values.

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 process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

What is the process for list.map to handle waiting for a request response?

I'm facing an issue with my map function where it is not waiting for the request response before moving on to the next index. this.products = []; productList.map((product) => { this.productService.getProductInfo(product).subscribe(productData => ...

An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet: Definition of Interface - interface IWEXInterface { readonly Date?: string; "Exec Qty"?: string; readonly Expiry?: string; } Data Collection - let data: IWEXInterface[] = [ { Date: &qu ...

Data binding in Angular 2: Connecting components

Is it possible to establish a connection between two components that are working with related objects? One of the components is dedicated to filtering, while the other displays the data results. By applying filters such as checkboxes, the displayed data ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

Error: Virtual script not located; possibly absent <script lang="ts" / "allowJs": true / within the jsconfig.json.volar

https://i.sstatic.net/dFaVQ.png I noticed an error in my footer component in VueJs (TypeScript template) as depicted by the image showing blue squiggly lines. ...

Encountering problem while upgrading Angular Material from version 13 to 14 - error TS2307: Module '@angular/material/core/common-behaviors/constructor' not found

While upgrading Angular and Angular Material from version 13.2.6 to 14.2.2, I encountered the following challenges: Error TS2307: Module '@angular/material/core/common-behaviors/constructor' or its type declarations cannot be found. Error TS2345 ...

Learn how to hide the dropdown menu in Angular 8 by detecting clicks outside of the menu area

Is there a way to hide the custom dropdown menu whenever I click outside of it? After trying the code below, I noticed that it hides even if I click on an element inside the dropdown menu: <button class="btn btn-primary btn-sm mt-1" type="button" id= ...

Data fetched using React Query

When using React Query to fetch data, the function runs smoothly. After console.logging the 'data' variable from React Query, it prints an array of objects as expected and handles states efficiently between loading, success, error. The issue ar ...

After each save, gulp-typescript is emitting errors, however, it works without any issues upon subsequent saves

I'm facing some uncertainty regarding whether the issue I'm encountering is related to gulp, typescript, or Angular 2. Currently, I am using Angular 2 Beta 6. Here is an example of my typescript gulp task: var tsProject = p.typescript.createPr ...

Encountered an issue with a module not being found while trying to install a published React component library that is built using Rollup. The error message states:

In my latest project, I have developed a React component library called '@b/b-core' and used Rollup for building and publishing to the repository. When trying to install the library in a React app, an issue arises where it shows Module not found: ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Unable to retrieve dynamically generated object property from an array in AngularJS 2+

Here is an example of an items array: this.itemList = [ { id: 1, name: 'a', address: 'as dasf a' }, { id: 2, name: 'b', address: 'as dasf a' }, { id: 3, name: 'c', address: 'as dasf a' } ]; ...

What is the best way to bring in a variable initialized by an IIFE from a JavaScript file into a TypeScript class?

I'm currently working towards integrating the steelseries.js library (found at https://github.com/HanSolo/SteelSeries-Canvas) into a Grafana plugin built with React. It's quite a complex task, but I'm up for the challenge. Right now, my ma ...

What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date? let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + currentSelection.startTimeAMPM; let endTime = currentSelection.stopTimeHr + ":" + currentSele ...

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

Navigating through the exported components of a module without explicit type declarations

So I'm in the process of developing a module with sub-modules for Angular. Here's the notation I'm using: module App.services { export class SomeService { } } When initializing all services, I use the following code snippet: function ...

Exploring the implementation of a custom validator within an Angular service

I have been attempting to implement a custom validator to validate if an email is already in use. After consulting the documentation and reading various articles, I have come up with the following code: In my auth.service.ts file checkEmail(email) { ...

Encountering data loss while mapping for the first time in React Native using useState - any solutions?

const initialData = [ { id: 1, name: `${accountList?.brideName} ${accountList?.brideSurname}`, type: 'Gelin', selected: false, tlText: accountList?.brideAccount?.accountTl, euroText: accountList?.brideAccou ...