Angular 4 typescript parsing enum interface attribute in response object

南楼画角 提交于 2020-12-30 02:29:06

问题


I have a response from API which is returning a enum value. value returned from API is represented as a string in request. This value is a enum attribute of typescript interface.

Problem: when receiving a response, TS interface store that value as a string (probably thats the issue) so i can't use it directly as enum.

obj 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());
      });
    }

usage sample:

    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;
      }
    }

So, the switch.. caseis not working for this attribute. in console.log() i'm getting:

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

console.log(typeof LocationType.CONDO) - number

So, that means that there were a parsing prob and condo_list[i].locationType is not a enum (considering it should show number for enum)?

How should i fix it?


回答1:


If you're using typescript 2.4 or above, you can declare string enums as follows:

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

// ...

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

In older versions, you're restricted to using number-based enums. In that case, you're probably better off using a string literal union type:

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

// ...

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


来源:https://stackoverflow.com/questions/45539033/angular-4-typescript-parsing-enum-interface-attribute-in-response-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!