How to make prop mandatory based on another prop being passed

Viewed 279

I have some code for a form:

interface FormProps {
  regexPreset?: RegexPresets;
  customRegex?: RegExp;
  description?: string;
  inputTitle: string;
  errorMessage?: string;
}
const Form: React.FC<FormProps> = props => {
  return <div> somestuff </div>
} 

If I pass in a customRegex, I want the compiler to throw an error if errorMessage is not passed (make errorMessage a mandatory property).

The closest thing that I've come to is this StackOverflow post, but I'm unsure whether I can apply this to my use case.

Any pointers would be gladly received.

1 Answers

I think it's feasible to utilize what's mentioned in that post you mentioned in your post, but before going into advanced typings I'd like to evaluate if the simplest solution possible is sufficient. So–if you were to include a customRegex, you would be forced to also include a errorMessage–then this type should cover your use-case:

interface FormProps {
  regexPreset?: RegexPresets;
  description?: string;
  inputTitle: string;
  customRegexProps?: {
    customRegex: RegExp;
    errorMessage: string;
  }
}
Related