Angular项目中TypeScript如何处理含@的JSON字段?
解决TypeScript中访问带@前缀的JSON字段问题
在TypeScript/JavaScript中,当属性名包含@这类非标准标识符字符时,不能使用点语法直接访问,必须改用方括号语法来获取字段值。
具体实现
错误写法(会触发编译错误):
this.timestamp = response.@timestamp;
正确写法:
// 用字符串形式的字段名包裹在方括号中 this.timestamp = response['@timestamp'];
类型定义补充
如果需要为返回的响应数据定义TypeScript接口,同样要在接口中用字符串形式声明该字段:
interface ApiResponse { '@timestamp': string; // 其他接口字段... } // 发起请求并指定类型 const response = await this.http.post<ApiResponse>('/api/endpoint', postData).toPromise(); this.timestamp = response['@timestamp'];
这种方式不仅适用于@前缀的字段,任何包含特殊字符、空格或关键字的属性名,都可以用方括号语法来访问。
内容的提问来源于stack exchange,提问作者Alaychem goes to Codidact
相关产品推荐
相关产品推荐

