Search code examples
reactjstypescriptreact-props

In Typescript how to make a property required if another optional property is set?


I am not sure, what to search for below requirement. I am using the below type for react props.

interface ComponentProps {
   message : string,
   minValue? : number,
   minValueValidationMessage? :string
}

Now, I want to let the typescript know that, if minValue is specified then minValueValidationMessage should also be required.

if minValueValidationMessage is specified, then minValue should also be specified.

I have quite a few similar such combinations and can happen in any permutation and combination.


Solution

  • You can try the below one.

    interface ComponentProps {
       message : string,
       min? : {value : number, validationMessage : string},
       max? : {value : number, validationMessage : string},
    }
    

    When using props you can specify

    <Component 
        message={"Hello World"} 
        min={{value:10,vaidationMessage:"Value should be more than 10"}}
    />
    

    If {value : number, validationMessage : string} repeats then it can be extracted to separate type.