如何在React子组件中传递单个TypeScript Interface对象作为Props
解决React+TypeScript子组件传递单个对象Props的问题
问题场景
刚接触TypeScript和React,需要在子组件中传递单个TypeScript对象作为Props。尝试参考对象数组传递的方案修改代码后报错,错误信息如下:
ERROR in src/App.tsx:23:14 TS2322: Type '{ user: IUserType | undefined; }' is not assignable to type 'IntrinsicAttributes & IUserType'. Property 'user' does not exist on type 'IntrinsicAttributes & IUserType'. 21 | }} 22 | /> > 23 | <Child user={user} /> | ^^^^ 24 | </> 25 | ); 26 | }
现有代码
类型定义(ApiInterface.ts)
export type IUserType = { id: number; name: string; username: string; email: string; };
父组件(Parent.tsx)
import { useEffect, useState } from "react"; import { IUserType } from "./ApiInterface"; import "./App.css"; import Child from "./Child"; export default function App() { const [user, setUser] = useState<IUserType>(); useEffect(() => { fetch(`https://jsonplaceholder.typicode.com/users/1`) .then((res) => res.json()) .then((res) => setUser(res as IUserType)); }, []); return ( <> <Child user={user} /> </> ); }
子组件(Child.tsx)
import { IUserType } from "./ApiInterface"; const Child: React.FunctionComponent<IUserType> = (user): JSX.Element => { return <div>{JSON.stringify(user)}</div>; }; export default Child;
错误原因
- 子组件Props类型定义错误:直接将
IUserType作为子组件的Props类型,但父组件传递的是包含user字段的对象,而非IUserType本身。子组件的Props应该是一个包含user属性的类型,属性值为IUserType | undefined(父组件中user状态初始为undefined)。 - 未处理undefined状态:父组件中
user初始值为undefined,子组件未做对应处理,可能引发渲染问题。
修正方案
1. 修正子组件的Props类型
重新定义子组件的Props类型,明确接收名为user的属性,并处理undefined情况:
import { IUserType } from "./ApiInterface"; // 定义子组件专属的Props类型 type ChildProps = { user: IUserType | undefined; }; const Child: React.FunctionComponent<ChildProps> = ({ user }): JSX.Element => { // 当user未加载完成时显示占位内容 if (!user) { return <div>加载中...</div>; } return <div>{JSON.stringify(user)}</div>; }; export default Child;
2. 可选优化:父组件添加条件渲染
在父组件中仅当user存在时渲染子组件,避免传递undefined:
// 父组件return部分修改为 return ( <> {user && <Child user={user} />} </> );
此时子组件的Props类型可简化为:
type ChildProps = { user: IUserType; }; const Child: React.FunctionComponent<ChildProps> = ({ user }): JSX.Element => { return <div>{JSON.stringify(user)}</div>; };
总结
核心问题是子组件的Props类型与父组件传递的属性结构不匹配。通过明确子组件的Props结构,并处理状态的undefined情况,即可解决报错问题。
内容的提问来源于stack exchange,提问作者stacy anderson
相关产品推荐
相关产品推荐

