StencilJS组件传递对象数组Prop时无法访问label属性的问题
解决TypeScript中“Property 'label' does not exist on type 'object'”错误
问题场景
你在开发列表组件时,通过以下方式传递数据:
HTML代码:
<ps-list> </ps-list>
JavaScript代码:
const listCollection = [ {label: "Link One"}, {label: "Link Two"}, {label: "Link Three"}, {label: "Link Four"} ] document.querySelector('ps-list').listItems = listCollection
Prop定义:
@Prop() listItems: object[]
遍历数组时执行以下代码报错:
this.listItems.map((item: object) => { console.log(item.label) })
错误信息:"Property 'label' does not exist on type 'object'"
解决方案
1. 定义明确的接口/类型
创建接口描述列表项的结构,让TypeScript识别label属性:
// 定义接口 interface ListItem { label: string; } // 修改Prop的类型定义 @Prop() listItems: ListItem[]; // 遍历访问label this.listItems.map((item: ListItem) => { console.log(item.label); });
2. 使用类型断言
直接在遍历过程中告诉TypeScript当前对象的结构:
// as语法 this.listItems.map((item) => { console.log((item as { label: string }).label); }); // 尖括号语法(JSX环境下不推荐,可能与标签冲突) this.listItems.map((item) => { console.log((<{ label: string }>item).label); });
3. 使用索引签名
如果列表项的属性不确定,但确认包含label,可以用索引签名放宽类型限制:
// 修改Prop定义 @Prop() listItems: { [key: string]: any }[]; // 遍历访问label this.listItems.map((item) => { console.log(item.label); });
原因说明
TypeScript的object类型是通用类型,仅表示该值是对象,但不包含任何具体属性的类型信息。编译时TypeScript无法确认item上存在label属性,因此抛出错误。而typeof item返回的是JavaScript运行时的类型,和TypeScript编译时的类型检查逻辑不同。
内容的提问来源于stack exchange,提问作者iChido
相关产品推荐
相关产品推荐

