无法访问JSON对象的totals属性,TypeScript类型报错原因解析
问题:访问JSON属性时出现TypeScript类型错误
原始JSON数据
data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ { "type": { "he": "מאזן", "en": "Balance Sheets" }, "fin_statement": "BS", "sections": [ { "section_name": { "he": "נכסים שוטפים", "en": "Current Assets" }, "totals": { "2020": { "final_total_local": 100000, "final_total_foreign": 0 }, "2021": { "final_total_local": 110000, "final_total_foreign": 0 } }, "subsections": [ {......(the rest is irrelevant) } ] } ] }
报错信息
Element implicitly has an 'any' type because expression of type "totals" can't be used to index type
原因
这是TypeScript的类型检查机制导致的问题:你没有给data定义明确的类型结构,TS无法自动推断出sections数组里的元素包含totals这个属性,所以当你用['totals']索引访问时,TS会认为这个索引操作的目标类型不确定,抛出“隐式any类型”的错误。
解决方法
临时快速处理(不推荐长期使用)
用类型断言强制告诉TS这个元素的类型,跳过类型检查:
(data.reports[0].sections[0] as any)['totals']
这种方法虽然能快速解决报错,但会失去TypeScript类型检查的优势,容易埋下潜在bug。
规范解决方案(推荐)
给数据定义对应的TypeScript接口,明确整个数据的结构:
// 定义年份总计的类型 interface YearTotal { final_total_local: number; final_total_foreign: number; } // 定义章节类型 interface Section { section_name: { he: string; en: string; }; totals: Record<string, YearTotal>; subsections: any[]; // 可以根据实际子结构细化类型 } // 定义报告类型 interface Report { type: { he: string; en: string; }; fin_statement: string; sections: Section[]; } // 定义整个审计数据的类型 interface AuditData { company_name: string; audit_period_begin: string; audit_period_end: string; reports: Report[]; } // 给data指定类型 const data: AuditData = { // 你的原始JSON数据内容 };
定义完类型后,再通过data.reports[0].sections[0].totals访问属性就不会报错了,同时还能获得TS的类型提示和检查。
内容的提问来源于stack exchange,提问作者nuriel wainstein
相关产品推荐
相关产品推荐

