TypeScript类型报错:对象无法赋值给Notification[]类型
解决TypeScript类型不兼容问题
核心问题分析
报错源于两个关键问题:
- 数据结构不匹配:传入的是单个Notification对象,但
Notifications组件要求接收Notification[](对象数组)类型 - 接口属性缺失:
Notification接口定义了requested属性,但JSON数据中没有该字段,TypeScript会严格校验属性完整性
解决方案步骤
1. 修正数据结构,传入数组类型
将单个JSON对象包装成数组,确保传给组件的是数组格式:
// 把导入的JSON数据包装为数组 const data1 = [ {"username": "kahlilsassa ", "profileImage": "https://pbs.twimg.com/profile_images/1587301092680941569/B2GsgnBg_400x400.jpg", "seen": true, "followed": true, "verified": false, "datePosted": "2022-11-01:11:09" } ]; // 组件中正常使用 <Notifications notifications={data1} />
2. 处理缺失的requested属性
有两种可选方案:
方案一:给JSON补充
requested字段
按照接口要求给JSON对象添加requested字段,值设为null或空数组:{"username": "kahlilsassa ", "profileImage": "https://pbs.twimg.com/profile_images/1587301092680941569/B2GsgnBg_400x400.jpg", "seen": true, "followed": true, "verified": false, "datePosted": "2022-11-01:11:09", "requested": null }方案二:修改接口,将
requested设为可选属性
如果requested不是每个通知的必填项,在接口中用?标记为可选:// 先补充缺失的Requested类型定义(TypeScript类型名通常首字母大写) interface Requested { // 按需添加业务属性,例如: // id: string; // action: string; } export interface Notification { requested?: Requested[] | null; // 加?标记为可选属性 username: string; profileImage: string; seen: boolean; followed: boolean; verified: boolean; datePosted: string; }
3. 修复未定义的requested类型
代码中使用了Array<requested>但未定义该类型,必须补充Requested接口,否则会出现“Cannot find name 'requested'”的额外报错。
修改后的完整示例
Notification组件
// 补充Requested接口 interface Requested { // 根据业务需求添加属性 } interface Props { notifications: Notification[] | null; } export interface Notification { requested?: Requested[] | null; username: string; profileImage: string; seen: boolean; followed: boolean; verified: boolean; datePosted: string; }
Home组件
const data1 = [ {"username": "kahlilsassa ", "profileImage": "https://pbs.twimg.com/profile_images/1587301092680941569/B2GsgnBg_400x400.jpg", "seen": true, "followed": true, "verified": false, "datePosted": "2022-11-01:11:09" } ]; <Modal active={notifications} setActive={setNotifications} title="Notifications"> <div className="divider"> <Notifications notifications={data1} /> </div> </Modal>
内容的提问来源于stack exchange,提问作者Kahlil Sassa
相关产品推荐
相关产品推荐

