TypeScript接口props定义后仍报services属性不存在错误求助
错误原因
React 函数组件的第一个入参是整体 props 对象,而非直接接收 props 下的单个字段。你当前将 BusinessPage 组件的入参声明为 services: AkkordionProps[],等于告知 TypeScript 该组件的整个 props 是 AkkordionProps 类型的数组,数组本身不存在 services 属性,和你调用时传入的 <BusinessPage services={services} /> 无法匹配,因此触发报错 Property 'services' does not exist on type 'IntrinsicAttributes & AkkordionProps[]。
修复方案
1. 修正组件入参的类型声明
你已经定义的 AkkordionProps 本身就是符合要求的 props 类型,直接将其作为组件整体 props 的类型即可,常用有两种写法:
- 解构 props 写法(推荐)
// 从整体props中解构出services字段,指定props的类型为AkkordionProps export const BusinessPage = ({ services }: AkkordionProps): JSX.Element => { // 组件业务逻辑 return <></> }
- 整体 props 接收写法
export const BusinessPage = (props: AkkordionProps): JSX.Element => { // 使用时通过props.services访问对应字段 console.log(props.services) return <></> }
2. 可选校验类型层级
你当前的类型定义层级如下:
AkkordionProps下的services字段类型为AkkordionListProps[]AkkordionListProps下的services字段类型为包含name、子级services数组的对象
如果传入的业务数据结构和上述层级匹配无需调整,否则对应修改 interface 的字段定义即可。
内容的提问来源于stack exchange,提问作者Peace Brother Peace
相关产品推荐
相关产品推荐

