NextJS组件传client属性提示无法分配给IntrinsicAttributes错误如何解决
错误原因
这个TypeScript报错的核心是你没有为ClientInfo组件显式声明包含client字段的Props类型。
你虽然在组件参数里写了{ client }: any,但由于组件标注了NextPage类型——NextPage是React函数组件的衍生类型,默认仅内置children等通用属性,未包含你自定义的client属性,所以TypeScript会判定传入client属于非法属性,抛出类型错误。
解决方法
按以下步骤调整类型定义即可:
- 先定义业务层面的Client数据结构和组件Props类型,可根据你的实际业务字段调整:
// 自定义Client数据结构 interface Client { id: number; name: string; // 补充其他client字段 } // ClientInfo组件的Props类型 interface ClientInfoProps { client: Client | null; }
- 修正
ClientInfo组件的类型标注,给NextPage传入Props泛型,同时可以删掉之前的any类型声明:
const ClientInfo: NextPage<ClientInfoProps> = ({ client }) => { return <div>{/* 原有组件逻辑 */}</div> }
- 给
selectedClient状态补全类型标注:
const [selectedClient, setSelectedClient] = useState<Client | null>(null);
如果你的业务场景下允许client初始为空对象,只需要把ClientInfoProps里的client类型改成Client | null | Record<string, never>即可。
内容的提问来源于stack exchange,提问作者Code Guru
相关产品推荐
相关产品推荐

