简体   繁体   中英

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.

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.

I like Vuetify's take on textfield validation

They declare rules prop on a textfield, that returns true if rule is passed or error string if not

// T will be type of value you want to validate, string for textfield for example
type ValidationRule<T> = (value: T) => true | string;
 
interface ComponentProps {
  message: string;
  rules: ValidationRule<string>[]
}

So now you can describe validation rules in parent component like so

<Component rules={[
  (value) => !!value || 'This field is required!',
  (value) => value.length < 10 || 'Length should be lesser than 10'
]}>

And loop through validaion rules inside the component to validate and display validation message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM