TypeScript中如何声明并访问带@前缀的属性(如@type)?
TypeScript 声明及访问带@前缀属性的解决方案
接口声明写法
TypeScript 中如果属性名包含@、空格、短横线等特殊字符,只需要用引号将属性名包裹即可完成声明:
export interface DataTypes { // 注意:接口返回的number字段是字符串格式的手机号,需对应声明为string类型 number: string; '@type': string; }
属性访问写法
带特殊字符的属性无法通过点语法直接访问,需要使用方括号语法访问,TypeScript 会自动匹配对应类型不会报错:
// 示例使用 const resData: DataTypes[] = // 接口返回的data数据 // 访问@type属性 console.log(resData[0]['@type']) // 输出 'mobile' // 普通属性访问方式不受影响 console.log(resData[0].number) // 输出 '02302030203'
内容的提问来源于stack exchange,提问作者user16691768
相关产品推荐
相关产品推荐

