如何修复'ReactElement<any, any>'缺少'SidebarInterface'属性的类型错误?
React组件类型错误排查与修复
问题现象
编写Sidebar组件时遇到TypeScript报错:
Type 'ReactElement<any, any>' is missing the following properties from type 'SidebarInterface': isOpen, toggle
原组件代码
Navbar组件
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> & { [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>> }[Keys] interface NavbarInterface { toggleSidebar: () => void, exclude: boolean, logoImg?: StaticImageData, logoText?: string, opacity: number } const NavBar = ({ toggleSidebar, exclude, logoImg, logoText, opacity }: RequireAtLeastOne<NavbarInterface, 'logoImg' | 'logoText'>) => { //code... return ( <Nav alpha={opacity} scrolled={scrolled} exclude={exclude}> {/* more react elements */} </Nav> ) }
Sidebar组件(报错版本)
interface SidebarInterface { exclude?: boolean, isOpen: boolean, toggle: () => void } const Sidebar = ({ exclude, isOpen, toggle }): SidebarInterface => { return ( <SidebarContainer isOpen={isOpen} onClick={toggle}> {/* more react elements */} </SidebarContainer> ) }
错误原因
Sidebar组件的返回类型标注错误:
SidebarInterface是定义组件接收的props的类型,而React组件的返回值应该是React元素(JSX.Element或React.ReactElement)。- 把组件的返回类型指定为props接口,导致TypeScript认为组件需要返回符合
SidebarInterface的对象,但实际返回的是React元素,两者类型不匹配,因此触发报错。
修复方案
修正Sidebar组件的返回类型,有两种可行方式:
方式1:明确指定返回类型为JSX.Element
import type { JSX } from 'react'; interface SidebarInterface { exclude?: boolean, isOpen: boolean, toggle: () => void } const Sidebar = ({ exclude, isOpen, toggle }: SidebarInterface): JSX.Element => { return ( <SidebarContainer isOpen={isOpen} onClick={toggle}> {/* more react elements */} </SidebarContainer> ) }
方式2:省略返回类型,让TypeScript自动推断
TypeScript可以自动识别React组件的返回类型,直接去掉返回类型标注即可:
interface SidebarInterface { exclude?: boolean, isOpen: boolean, toggle: () => void } const Sidebar = ({ exclude, isOpen, toggle }: SidebarInterface) => { return ( <SidebarContainer isOpen={isOpen} onClick={toggle}> {/* more react elements */} </SidebarContainer> ) }
额外说明
对比Navbar组件的写法,它没有指定返回类型,TypeScript自动推断为React元素,因此没有报错。Sidebar的核心问题就是把props类型误当成了返回类型,修正后即可解决报错。
内容的提问来源于stack exchange,提问作者Tara
相关产品推荐
相关产品推荐

