Decoding enum interface attribute from response object in Angular 4 using typescript

From an API response, I am receiving an enum value represented as a string. This enum value is part of a typescript interface.

Issue: Upon receiving the response, the TypeScript interface stores the value as a string, making it unusable directly as an enum.

Interface model:

export interface Condo {

  id:number
  title:string
  latitude:number
  longitude:number

  city:string
  country:string
  district:string
  address:string
  locationType: LocationType
}

export enum LocationType {
  CONDO,
  MALL,
  STATION
}

Request:

getCondoAllByCountry(country_code){
    return this.http.get(this.config.apiEndpoint +this.subApiUrl+'/all')
      .map(res => <Condo[]>res.json())
      .catch((err:Response) => {
        return Observable.throw(err.json());
      });
    }

Sample usage:

    this.condoService.getCondoAllByCountry(this.userData.country_code).subscribe(data=>{
          someFunc(data)
        })

............
    someFunc(condo_list: Condo[]){
    //here is need to know the `locationType` for each object
      console.log(typeof condo_list[i].locationType);
      console.log(typeof LocationType.CONDO)
      switch (condo_list[i].locationType){
        case LocationType.CONDO:
          console.log('Case - condo')
          break;
        case LocationType.MALL:
          console.log('Case - mall')
          break;
        case LocationType.STATION:
          console.log('Case - station')
          break;
      }
    }

The switch.. case statement is not working for this attribute. In the console.log(), I'm getting:

console.log(typeof condo_list[i].locationType);
- string

console.log(typeof LocationType.CONDO)
- number

This indicates there was a parsing issue and condo_list[i].locationType is not being recognized as an enum (as it should be shown as a number for enum).

How can I resolve this problem?

Answer №1

If you are working with TypeScript version 2.4 or newer, you can define string enums in the following way:

export enum LocationType {
  CONDO = 'CONDO',
  MALL = 'MALL',
  STATION = 'STATION'
}

// ...

switch (object.locationType) {
    case LocationType.CONDO: // ...
    case LocationType.MALL: // ...
    case LocationType.STATION: // ...
}

In older versions of TypeScript, you are limited to using enums based on numbers. In those cases, it is recommended to use a string literal union type instead:

export type LocationType = 'CONDO' | 'MALL' | 'STATION';

// ...

switch (object.locationType) {
    case 'CONDO': // ...
    case 'MALL': // ...
    case 'STATION': // ...
}

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

Production environment experiencing issues with FCM service worker functionality

Upon testing the production build on localhost, Firebase Cloud Messaging (fcm) functions correctly. However, when attempting to run it on my AWS EC2 instance, I encountered the following error: An Unhandled Promise rejection occurred: Messaging: We are un ...

Encountering an error when updating Angular 2 dynamic forms: "Expression has been altered"

I'm struggling with creating a dynamic nested form that's quite complex, but I just can't seem to get it functioning properly. Essentially, the end result should look similar to this: Desired outcome mockup The user will need to choose a f ...

Executing a HTTP POST request using a dialog component

In my component, list, I am displaying title names from an external API: https://i.sstatic.net/mA1MR.png The image above shows a fab-button labeled Add. When this button is clicked, it triggers a dialog window (component named add-customer) like so: htt ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

Creating an Angular 2 component that utilizes an interface within the constructor

If you have an interface named IData, and you want to develop an Angular 2 component that can accept any Class utilizing IData in its constructor, could this concept be implemented or is it off track? Your insights are greatly appreciated. ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

What is the method for determining the length of a piped array within a template?

Here is a sample code snippet showcasing how to get the length of an array when not using a pipe: <my-component [arrLen]='arrayA.length'></my-component> But what if you want to get the length of a filtered array using a pipe? The exa ...

Angular response object being iterated through in a loop

I am facing a challenge while trying to iterate through an array containing values that need to be displayed to the user. Despite receiving a response with the data, I am having trouble accessing and looping through the elements of the array using Angular. ...

UI5 Tooling generated an error stating that "sap is not defined" after a self-contained build

Having successfully developed an application using SAPUI5 1.108, I encountered a setback when attempting to deploy it to a system running SAPUI5 version 1.71. The older version lacks certain features, causing the application to fail. In order to address th ...

Issues with conditional types in TypeScript functionality not yielding desired results

Here is some TypeScript code that I am working with: type NumberOrNever<T> = T extends number ? T : never function f<T>(o: T) : NumberOrNever<T> { if (typeof o === "number") return o; throw "Not a number!" } ...

Is it possible to have a synchronous function imported in typescript?

// addons.ts export interface addon { name: string; desc: string; run: (someparam: any) => void; } export function loadaddons(): Array<addon> { let addons: Array<addon> = []; fs.readdirSync(path.join(__dirname, "addons")) .fi ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Tips for displaying the string value of an elementFinder when encountering an error in protractor

I have the following code snippet: export async function waitTillClickable(e: ElementFinder): Promise<ElementFinder> { const conditions = EC.visibilityOf(e); await browser.wait(conditions, DEFAULT_TIMEOUT, `Element did not return ...

Query parameters in Angular 5 that have a global scope

Adding a global query parameter to every path of the application is my goal (such as /my/path?config=foo). I prefer not to use the option to preserve query params because I only want to retain this specific one. The application operates with various confi ...

Is the Dropbox JavaScript SDK compatible with Ionic3?

Does anyone know how to integrate the Dropbox JavaScript SDK into an Ionic 3 app? Just a note: I have come across some sample examples using the http endpoint. ...

Angular Universal involves making two HTTP calls

When using Angular Universal, I noticed that Http calls are being made twice on the initial load. I attempted to use transferState and implemented a caching mechanism in my project, but unfortunately, it did not resolve the issue. if (isPlatf ...

Is it possible for me to change a selector value?

Currently, I am working on an app that utilizes NGRX. I have a question regarding the store being a readonly place where direct object mutation is not allowed. However, I am unsure about the use of selectors. For example, consider the following NGRX sele ...

Building a user interface in Angular2 that consists of multiple components and utilizes

What is the recommended structure for an Angular2 (beta3) application with routing when incorporating a parent/child multi-component setup? When dealing with individual tables, I have set up the following structure: https://i.stack.imgur.com/BYqGU.jpg I ...