React 18.2.0+TS报错:Type '{ children: Element; }'与IntrinsicAttributes无匹配属性
解决React+TypeScript中
Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'报错 这个报错的核心原因是你在定义AppStateProvider时,同时使用了React.FC类型标注和手动指定React.PropsWithChildren<{}>作为props类型,两者的类型定义产生了冲突。React.FC本身已经内置了对children属性的类型支持,手动添加的PropsWithChildren会导致TypeScript对组件props的类型校验出现矛盾。
修复方案有两种:
方案1:移除手动的props类型定义,使用React.FC的默认children支持
修改AppStateContext.tsx中的组件定义:
import React, { FC, useImmerReducer } from 'react'; // 导入你的AppStateContext、appStateReducer、appData export const AppStateProvider: FC = ({ children }) => { const [state, dispatch] = useImmerReducer(appStateReducer, appData) const { lists } = state const getTasksByListId = (id: string) => { return lists.find((list) => list.id === id)?.tasks || [] } return ( <AppStateContext.Provider value={{ lists, getTasksByListId, dispatch }}> {children} </AppStateContext.Provider> ) }
方案2:不使用React.FC,直接明确props类型
如果你更倾向于手动定义props类型,可以去掉FC标注,直接使用PropsWithChildren:
import React, { useImmerReducer, PropsWithChildren } from 'react'; // 导入你的AppStateContext、appStateReducer、appData export const AppStateProvider = ({ children }: PropsWithChildren<{}>) => { const [state, dispatch] = useImmerReducer(appStateReducer, appData) const { lists } = state const getTasksByListId = (id: string) => { return lists.find((list) => list.id === id)?.tasks || [] } return ( <AppStateContext.Provider value={{ lists, getTasksByListId, dispatch }}> {children} </AppStateContext.Provider> ) }
两种方案都能解决类型冲突问题,让TypeScript正确识别children属性,消除报错。
内容的提问来源于stack exchange,提问作者David Essien
相关产品推荐
相关产品推荐

