响应对象中的Angular 4打字稿解析枚举接口属性

use*_*987 2 typescript ionic2 angular

我有一个来自API的响应,该响应返回一个枚举值。从API返回的值在请求中表示为字符串。该值是enum打字稿界面的属性。

问题: 当收到响应时,TS接口将该值存储为字符串(可能就是问题所在),因此我不能将其直接用作enum

obj模型:

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
}
Run Code Online (Sandbox Code Playgroud)

请求:

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());
      });
    }
Run Code Online (Sandbox Code Playgroud)

用法样本:

    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;
      }
    }
Run Code Online (Sandbox Code Playgroud)

因此,switch.. case不适用于此属性。在console.log()我得到:

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

console.log(typeof LocationType.CONDO) -- number

因此,这意味着存在一个解析概率,condo_list[i].locationType而不是一个解析概率enum(考虑它应该显示number为枚举)?

我该如何解决?

Rob*_*sen 6

如果您使用的是打字稿2.4或更高版本,则可以声明字符串枚举,如下所示:

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

// ...

switch (object.locationType) {
    case LocationType.CONDO: // ...
    case LocationType.MALL: // ...
    case LocationType.STATION: // ...
}
Run Code Online (Sandbox Code Playgroud)

在旧版本中,您只能使用基于数字的枚举。在这种情况下,最好使用字符串文字联合类型:

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

// ...

switch (object.locationType) {
    case 'CONDO': // ...
    case 'MALL': // ...
    case 'STATION': // ...
}
Run Code Online (Sandbox Code Playgroud)