【问题标题】:How do I fix the error `Type 'ReactElement<any, any>' is missing the following properties from type 'SidebarInterface': isOpen, toggle`?如何修复错误“Type \'ReactElement<any, any>\' 缺少类型 \'SidebarInterface\' 中的以下属性:isOpen,toggle”?
【发布时间】:2022-11-18 04:09:48
【问题描述】:

我有两个 React 组件,据我所知,它们的设置完全相同。第一个是导航栏:

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>
    )
}

有人可以帮我弄清楚这里发生了什么吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您过早关闭了参数声明:

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

    你有过

    }): SidebarInterface => {
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2021-10-02
      • 2019-09-08
      • 2017-09-14
      • 2019-04-28
      相关资源
      最近更新 更多