2

quick question - let's say I have a component like this:

interface ComponentInterface {
    nameA: string;
    nameB?: string;
}

const Component: React.FC<ComponentInterface> = (props) => {
     const { nameA, nameB } = props 
     const name = nameB || nameA;

     return <div>Hello World! Name: {name}</div>
}

is there a way in Typescript to make nameB mandatory if we don't pass nameA?

It feels bad to write <Component nameA={""} nameB={"John"} /> and I dont want to turn nameA into nameA?: string because I want at least one of the props to be passed.

This is an oversimplified version ofc. Ty in advance! <3

ChronicLogic
  • 313
  • 3
  • 17

1 Answers1

6

Yes, You can use union type:


interface Props1 {
    nameA: string;
    nameB?: string;
}

interface Props2 {
    nameB: string;
}

type Props = Props1 | Props2

It is mean, if you pass nameA, nameB is optional. But if you don't pass nameA - nameB is required.