React TypeScript报错:Property does not exist on interface 求解答及选型建议
问题解答
1. 代码错误原因及修正
报错'props does not exist on SmbListItem'的核心问题是组件props的类型定义与解构逻辑不匹配:你将组件的props类型指定为SmbListItem,但在解构时试图提取props字段,而SmbListItem接口中并没有定义这个字段,TypeScript因此报错。
针对你的需求,有两种正确写法:
写法一:直接接收模型字段作为组件props
如果希望组件直接接收index、primary、secondary作为独立props,代码调整如下:
import React from 'react' interface SmbListItem { index: number; primary: string; secondary: string; } export default function SmbList({ index, primary, secondary }: SmbListItem) { return ( <> <span>序号:{index}</span> <h3>{primary}</h3> <p>{secondary}</p> </> ); }
写法二:接收整个模型作为单个props参数
如果需要把整个SmbListItem对象作为一个名为props的参数传入,需要先定义组件的props接口,包含对应的字段:
import React from 'react' interface SmbListItem { index: number; primary: string; secondary: string; } // 定义组件专属的props接口 interface SmbListProps { props: SmbListItem; } export default function SmbList({ props }: SmbListProps) { return ( <> <span>序号:{props.index}</span> <h3>{props.primary}</h3> <p>{props.secondary}</p> </> ); }
另外注意:React的导入规范是import React from 'react'(首字母大写),虽然新版本React支持小写,但大写写法更符合社区规范。
2. interface与type的选择建议
在React组件props模型的场景下,优先使用interface,原因如下:
- interface专门用于定义对象/类的结构,支持声明合并(多次定义同一个interface会自动合并属性),更适配组件props的扩展需求;
- 社区中React组件的props类型定义普遍使用interface,可读性和一致性更好。
而type更适合这些场景:
- 定义联合类型(如
type Status = 'active' | 'inactive')、交叉类型; - 给基本类型、函数类型起别名。
内容的提问来源于stack exchange,提问作者Sandeep Thomas
相关产品推荐
相关产品推荐

