Samuel
Samuel

Reputation: 2635

TypeScript: Extend props in React component conditionally

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

Upvotes: 5

Views: 1867

Answers (1)

Alex
Alex

Reputation: 1849

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

Upvotes: 2

Related Questions