React和Typescript组件为`Component`提供道具类型

时间:2019-03-05 14:10:50

标签: reactjs typescript

我在React中有以下HOC:

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

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

我如何定义道具,以便打字稿对此感到满意?

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

我尝试了

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

如何在这里处理...rest

2 个答案:

答案 0 :(得分: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传递给组件时,我们确实需要使用类型断言,因为typescript无法确定{ Component: C, showIfTrue: boolean} & React.ComponentProps<C>减去ComponentshowIfTrue只是React.ComponentProps<C>,但您不可能拥有全部:)

答案 1 :(得分:0)

尝试一下:

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