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?