Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

reactjs - Mutually exclusive props in a React Component

How do I make sure my functions components props are mutually exclusive, with code completion?

My code:

type Variant =  'a' | 'p' | 'span' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'button'

interface TypographyProps {
    children: React.ReactNode | string
    className?: string | string[]
    variant?: Variant
}

type Text = TypographyProps
type Primary = TypographyProps & { primary: true }
type Secondary = TypographyProps & { secondary: true }
type Extra = TypographyProps & { extra: true }
type Dark = TypographyProps & { dark: true }
type Muted = TypographyProps & { muted: true }

function Typography(props: Text): JSX.Element;
function Typography(props: Primary): JSX.Element;
function Typography(props: Secondary): JSX.Element;
function Typography(props: Extra): JSX.Element;
function Typography(props: Dark): JSX.Element;
function Typography(props: Muted): JSX.Element;
function Typography({ children, className, variant, ...props }: TypographyProps): JSX.Element {

}

In WebStorm, when using control+spacebar (code completion), I don't get hints for props like primary or secondary. When I use more than one prop, I always get the error the first prop doesn't exist on type Muted.

e.g.

<Typography primary secondary>Foo</Typography>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Usually I consider a best practice to use only one props for exclusive parameters instead of multiple boolean props:


type Variant =  'a' | 'p' | 'span' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'button'

interface TypographyProps {
    children: React.ReactNode | string
    className?: string | string[]
    variant?: Variant
    type?: 'primary' | 'secondary' | 'extra' | 'dark' | 'muted'
}

function Typography({ children, className, variant, type, ...props }: TypographyProps): JSX.Element {

}

// e.g
<Typography variant="a" type="primary" />

I know it does not fully answer your question, but IMO it will reduce code complexity and allow better extensibility.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...