typescript 如何修复错误`类型'ReactElement〈any,any>'缺少类型'SidebarInterface'的以下属性:是否打开,切换'?

czq61nw1  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(146)

我有两个React组件,据我所知,它们的设置完全相同。第一个是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>
    )
}

第二个是侧边栏:

interface SidebarInterface {
    exclude?: boolean,
    isOpen: boolean,
    toggle: () => void
}

const Sidebar = ({
    exclude,
    isOpen,
    toggle
}): SidebarInterface => {
    return (
        <SidebarContainer isOpen={isOpen} onClick={toggle}>
            {/* more react elements */}
        </SidebarContainer>
    )
}

谁能帮我弄清楚这是怎么回事?

zbdgwd5y

zbdgwd5y1#

您过早地关闭了参数声明:

const Sidebar = ({
    exclude,
    isOpen,
    toggle
}: SidebarInterface) => { // parentheses goes AFTER props type
    return (
        <SidebarContainer isOpen={isOpen} onClick={toggle}>
            {/* more react elements */}
        </SidebarContainer>
    )
}

你有

}): SidebarInterface => {

它被视为返回类型。您返回的元素显然与prop类型不匹配。这就是TypeScript抛出错误(返回类型不匹配)的原因。

相关问题