5

Im trying to extend my component props conditionally depending on if a particular prop is passed.

My aim is to extend props by attributes of an anchor if a href prop is passed, and extend by attributes of a button if not.

Is this even possible?

Here's my attempt:enter image description here

5
  • 3
    Please don't post images please. Use the code formatting features of SO instead. Commented Aug 9, 2019 at 19:07
  • Will do, thanks for the pro tip Commented Aug 9, 2019 at 19:09
  • you can cast the component itself <Button<Anchor> ...></Button> and then update the definition export const Button<T> = (p: Props<T>). The type definition would just extend then type Props<T> = {...} & T Commented Aug 9, 2019 at 19:11
  • Thanks John, good idea. I wonder if there is any way for this to work conditionally in the component itself without explicit casting Commented Aug 9, 2019 at 19:17
  • That would look something like this. codesandbox.io/s/react-typescript-3c07h Commented Aug 9, 2019 at 19:29

1 Answer 1

2

Can't you just define properties as union type and use typeguard? Something like this:

type ButtonProps = { onClick: () => {} }
type LinkProps = { href: string }

type BaseProps = {
    spinner?: boolean
}

type Props = BaseProps & (ButtonProps | LinkProps)

export const Button = (props: Props) => {
    if ('href' in props) {
        // Link
    } else {
        // Button
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your suggestion @Aleksey but im seeing incompatible types now? How would i get around this: codesandbox.io/s/cocky-cohen-27cpw

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.