gpt4 book ai didi

Angular 4 typescript 解析响应对象中的枚举接口(interface)属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:39 25 4
gpt4 key购买 nike

我收到来自 API 的响应,它返回一个枚举值。从 API 返回的值在请求中表示为字符串。该值是 typescript 接口(interface)的 enum 属性。

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

对象模型:

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
}

要求:

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

使用示例:

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

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

console.log(typeof condo_list[i].locationType); - 字符串

console.log(typeof LocationType.CONDO) - 编号

所以,这意味着存在解析问题,并且 condo_list[i].locationType 不是 enum(考虑到它应该显示 number 对于枚举)?

我该如何解决?

最佳答案

如果您使用的是 typescript 2.4 或更高版本,您可以按如下方式声明字符串枚举:

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

// ...

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

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

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

// ...

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

关于Angular 4 typescript 解析响应对象中的枚举接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45539033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com