1

I have the following HOC in React:

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

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

How do I define the props so that Typescript will be happy with it?

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

I tried

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

How do I handle the ...rest here?

1
  • I'm not sure I follow, in typescript if you want to denote that your component doesn't need to have all the properties you can use Partials Commented Mar 5, 2019 at 14:21

2 Answers 2

2

If you want to preserve type safety, you need to make ConditionalSwitch generic and have it infer the full props passed to the component based on the actual value of Component. This will ensure that the client of ConditionalSwitch will pass in all the required properties of the used component. To do this we use the approach described 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

When passing the rest to the component we do need to use a type assertion because typescript is not able to figure out that { Component: C, showIfTrue: boolean} & React.ComponentProps<C> minus Component and showIfTrue is just React.ComponentProps<C> but you can't have it all :)

Sign up to request clarification or add additional context in comments.

5 Comments

I get the left hand side of an arithmetic operation must be... on the ? <Component {...(rest as any)} line
@mikeb works for me. What version of ts are you using ?
Typescript is 3.3.3333
@mikeb github.com/dragomirtitian/so-answers/tree/so-55004765 I tried on 3.3.1 and 3.4 (don't have 3.3.3333 right now)
I restarted Intellij and now I get Cannot find name Component right after the ? - it's like it does not see that it is an argument.
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.