【问题标题】:React & Typescript component props type for `Component``Component` 的 React 和 Typescript 组件道具类型
【发布时间】:2019-07-27 00:51:49
【问题描述】:

我在 React 中有以下 HOC:

`restricted` prop
    const ConditionalSwitch = ({component: Component, showIfTrue, ...rest}) => (

    showIfTrue
        ? <Component {...rest}/>
        : null
);

如何定义 props 以便 Typescript 满意?

{component: Component, showIfTrue, ...rest}

我试过了

export interface CSProps {
    component: any,
    showIfTrue: boolean
}

这里如何处理...rest?

【问题讨论】:

  • 我不确定我是否遵循,如果您想在 typescript 中表示您的组件不需要具有您可以使用的所有属性Partials

标签: reactjs typescript


【解决方案1】:

试试这个:

export interface CSProps {
    component: any;
    showIfTrue: boolean;
    [key: string]: any;
}

【讨论】:

    【解决方案2】:

    如果你想保持类型安全,你需要使ConditionalSwitch泛型,并让它根据Component的实际值推断传递给组件的完整道具。这将确保ConditionalSwitch 的客户端将传入所用组件的所有必需属性。为此,我们使用here 描述的方法:

    const ConditionalSwitch = <C extends React.ComponentType<any>>({ Component,  showIfTrue, ...rest}: { Component: C, showIfTrue: boolean} & React.ComponentProps<C> ) => (
        showIfTrue
            ? <Component {...(rest as any) }/>
            : null
    );
    
    function TestComp({ title, text}: {title: string, text: string}) {
        return null!;
    }
    
    let e = <ConditionalSwitch Component={TestComp} showIfTrue={true} title="aa" text="aa" />  // title and text are checked
    

    将rest 传递给组件时,我们确实需要使用类型断言,因为打字稿无法确定{ Component: C, showIfTrue: boolean} &amp; React.ComponentProps&lt;C&gt; 减去Component 和showIfTrue 只是React.ComponentProps&lt;C&gt;,但你不能拥有一切:)

    【讨论】:

    • 我在? &lt;Component {...(rest as any)} 线上收到the left hand side of an arithmetic operation must be...
    • @mikeb 为我工作。你用的是什么版本的ts?
    • Typescript 是 3.3.3333
    • @mikeb github.com/dragomirtitian/so-answers/tree/so-55004765 我试过 3.3.1 和 3.4(现在没有 3.3.3333)
    • 我重新启动了 Intellij,现在我在 ? 之后得到了 Cannot find name Component - 就像它没有看到它是一个参数一样。
    猜你喜欢
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 2020-03-09
    • 2019-06-21
    • 2018-08-08
    相关资源
    最近更新 更多