Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 485
Samuel Avatar asked Aug 09 '19 19:08

Samuel


1 Answers

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
    }
}
like image 108
Aleksey Avatar answered Nov 05 '22 04:11

Aleksey