Axios请求中$type属性反序列化异常问题求助
Axios请求中$type属性反序列化异常问题求助
大家好,我遇到了一个非常奇怪的类型映射问题,想请各位帮忙排查下:
我维护一个Vue.js项目,通过REST请求和.NET后端交互,后端返回的JSON里带有$type属性——因为接口返回的数组中包含多种类型的对象,后端用这个字段来标识具体类型。
相关代码实现
数据请求逻辑
public async getMyDataById(id: string): Promise<PayloadType> { this.endpoint = `${this.endpoint}/${articleId}`; const response = (await this.list()) as unknown as PayloadType; return response; } public async list(): Promise<PaginatedResponse<any>> { this.resolveEndpoint(); try { const response = await new Http().apiServer().get(this.endpoint); console.log('List response: '); console.log(response); return response.data as unknown as PaginatedResponse<any>; } catch (error) { await new NetworkError(error as AxiosError).handle(); useLogs().trackException(error as Error); throw error; } }
Axios实例配置
public apiServer(): AxiosInstance { return axios.create({ baseURL: this.configuration.API_URL, }); }
TypeScript类型定义
export type PayloadType = { content: ContentType; statusType: TStatus; otherValue: number; }; export type ContentType= { elementsList: ElementType[]; }; export type ElementType = { index: number; segments: Segment[]; } export enum SegmentType { TypeA = 'typea', TypeB = 'typeb', } export interface Segment { $type: SegmentType; index: number; title: string; } export interface TypeASegment extends Segment { $type: SegmentType.TypeA; htmlContent: string; }; export interface TypeBSegment extends Segment{ $type: SegmentType.TypeB someBooleanValue: boolean; someOtherChildComponents: OtherChildComponentType[]; };
诡异的问题现象
我有两个接口返回不同结构的JSON:
- 第一个接口返回完整的
PayloadType结构(包含content、status、otherValue),但打印响应时发现所有segments里的$type都被映射成了"typea"——明明后端返回的是前两个为typeb,第三个为typea; - 第二个接口直接返回第一个接口里的
content部分,这时$type却能被正确识别,前两个是typeb,第三个是typea。
我还特意调整过SegmentType的枚举值,结果发现所有类型都会被强制映射成TypeASegment里定义的$type值,而且哪怕我没有做任何显式的类型转换,这个问题依然会出现。
有没有朋友遇到过类似的问题?或者能帮我分析一下可能的原因?
备注:内容来源于stack exchange,提问作者Razvan
相关产品推荐
相关产品推荐

