Search code examples
reactjstypescriptreact-props

How to make a prop required based on condition typescript react


interface IPerson {
   name: string;
   gender: string;
   vaccinated: 'yes'|'no';
   vaccineName?: string
}

This interface describes vaccineName is optional and other properties are required. If property vaccinated is yes I need to make vacccineName property as required

<Person name='abc' gender='m' vaccinated='yes' />

Now this should throw error as vaccineName is required. Is this possible in react typescript


Solution

  • You can use TypeScript's discriminated unions to get compiler-time support for exactly what you're looking for.

    interface VaccinatedPersonProps {
       name: string;
       gender: string;
       vaccinated: 'yes';
       vaccineName: string
    }
    
    interface UnvaccinatedPersonProps {
       name: string;
       gender: string;
       vaccinated: 'no';
    }
    
    type PersonProps = UnvaccinatedPersonProps | VaccinatedPersonProps;
    
    function Person(props: PersonProps) {
      if (props.vaccinated === "yes") {
        // vaccinated!
        console.log(props.vaccineName);
      } else {
        // unvaccinated
      }
    };
    

    this article provides a more thorough write up: https://blog.andrewbran.ch/expressive-react-component-apis-with-discriminated-unions/