Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code:

export const enum ComplianceType {
  ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT',
  CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE',
  ARCHITECTURE_ASSIGNMENT = 'ARCHITECTURE_ASSIGNMENT',
  BLUEPRINT_APPROVAL = 'BLUEPRINT_APPROVAL',
  THERMAL_COMPLIANCE = 'THERMAL_COMPLIANCE',
  ELECTRICITY_COMPLIANCE = 'ELECTRICITY_COMPLIANCE',
  TELECOMUNICATION_COMPLIANCE = 'TELECOMUNICATION_COMPLIANCE',
  WATER_COMPLIANCE = 'WATER_COMPLIANCE',
  OTHER_1 = 'OTHER_1',
  OTHER_2 = 'OTHER_2',
}

In the .ts file:

import { ICompliance, ComplianceType } from 'app/shared/model/compliance.model';

Attempting to access the values with:

complianceTypeList: ComplianceType;

If you're unsure on how to get values from an enum in TypeScript, seeking advice would be helpful.

Answer №1

Your code structure is incorrect.

Instead of assigning, or attempting to assign Enums as variables, simply use export enum ComplianceType.

export enum ComplianceType {
  ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT',
  CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE',
  ARCHITECTURE_ASSIGNMENT = 'ARCHITECTURE_ASSIGNMENT',
  BLUEPRINT_APPROVAL = 'BLUEPRINT_APPROVAL',
  THERMAL_COMPLIANCE = 'THERMAL_COMPLIANCE',
  ELECTRICITY_COMPLIANCE = 'ELECTRICITY_COMPLIANCE',
  TELECOMUNICATION_COMPLIANCE = 'TELECOMUNICATION_COMPLIANCE',
  WATER_COMPLIANCE = 'WATER_COMPLIANCE',
  OTHER_1 = 'OTHER_1',
  OTHER_2 = 'OTHER_2',
}

After that, you can easily import the Enums into the necessary Class or component.

import { ComplianceType } from 'app/shared/model/compliance.model';

This approach works flawlessly on this platform.

Answer №2

To access the keys of your enums, you can use Object.keys(EnumType);. If you need to retrieve its values instead, you can utilize Object.values(EnumType);. However, it seems like you are attempting to assign an entire Enum to a single Enum property type in this case.

One way to achieve this is by:

complianceType: ComplianceType;

complianceType = ComplianceType.ENGINEER_ASSESMENT;

It is not logical to assign a type to a variable of this kind. It simply does not make sense.

Answer №3

To retrieve a value from an Enum, simply treat it as an array and access the value using the specific key:

ComplianceType["ARCHITECTURE_ASSIGNMENT"]

This method should return the desired value.

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

how to verify if a variable exists in TypeScript

Is there a recommended method for verifying if a variable has a value in TypeScript 4.2? My variable may contain a boolean value. I'm thinking that using if(v){} won't suffice as the condition could be disregarded if it's set to false. ...

Issue: Unhandled promise rejection: SecurityError: To use screen.orientation.lock(), the page must be in fullscreen mode

While attempting to change the orientation of one of my pages in an Ionic 3 app, I encountered the following error. The code snippet below was used to change from portrait mode to landscape mode: ionViewDidEnter() { // this.statusBar.hide(); // // ...

What causes the focus on input to be lost when using ngFor with a function that returns an array of objects?

When using *ngFor to iterate over an array of objects returned by a function, the focus blocks input preventing any typing. Strangely, this issue does not occur when the array of objects is directly inside the template. What could be causing this problem? ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

Clicking on a button to transfer items between pages (Ionic 2 + Angular 2)

I'm in the process of creating a recipe application and one feature I'd like to include is a shopping list page. On this page, users can click an "Add to Shopping List" button which will transfer the ingredients listed in a <ul> onto anothe ...

Encountering a "No overload matches this call" error while using React, Typescript, and d3js

Encountered an error in Typescript while using the scaleLinear() function from d3js. Seeking assistance in resolving this issue. The code is in React and utilizes typescript. Below is the source code: import React, { useRef, useState, useEffect } from &apo ...

What is preventing MenuItemLink from being displayed in the menu?

I have created a unique page for users to purchase subscriptions, but I am having trouble accessing that page because the button is not appearing in the menu. I followed the steps outlined in the official guide, but only the dashboard and resources buttons ...

Combining subscriptions in Angular

For the ngOnInit of a specific component, I have a need to subscribe to two different actions: To make a get request using an already existing Angular service that will return a list of items (sourceOptions in the code). To retrieve the route.queryParams ...

Angular appears to be unresponsive to callbacks

I currently have a small web application that features a wishlist functionality. While adding items to the list works fine, I am facing an issue with the delete operation in Angular. It seems like Angular does not wait for the response before navigating aw ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning. So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by m ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

The TypeScript command tsc -p ./ is causing errors in the typings modules

Whenever I try to execute the typescript command tsc -p ./, I encounter an error. This issue seems to be occurring with es6-shim and some other node packages. Below is my package.json: "scripts": { "vscode:prepublish": "tsc -p ./", "compile": "t ...

The unspecified value of a dynamically generated button

Currently, I am working on generating ion cards with a response. Each ion-card contains 3 buttons. I am able to receive the response properly, but I am facing an issue with assigning values to the buttons, or possibly implementing it incorrectly. Here is ...

An easy guide to using validators to update the border color of form control names in Angular

I'm working on a form control and attempting to change the color when the field is invalid. I've experimented with various methods, but haven't had success so far. Here's what I've tried: <input formControlName="pe ...

Error message: The object is not visible due to the removal of .shading in THREE.MeshPhongMaterial by three-mtl-loader

Yesterday I posted a question on StackOverflow about an issue with my code (Uncaught TypeError: THREE.MTLLoader is not a constructor 2.0). Initially, I thought I had solved the problem but now new questions have surfaced: Even though I have installed &apo ...

Show images from an array of base64 image data

I am currently facing an issue while trying to display images in base64 format within a RadListView component. Within the loop of the component, I have the following code snippet: let base64ImageSource = new ImageSource; base64ImageSource = fromBase64(re ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...

Adding FormControl dynamically to FormGroup can be achieved by simply using the appropriate method

Currently, I am working with a plunker where I am dynamically creating form components based on the model specified in app.ts. However, I am facing an issue where I cannot add formControlName = "name" to the component. In my control-factory.directive.ts ...