Dynamic TypeScript for Form Validation (and other things)
Something I've done once or twice with react-hook-form.
Say you had a type that defined some expected form value types.
Now say you wanted another that you're going to use to ensure that your validation functions take the correct value type as a function argument.
You could do the following:
type FormValues = {
name: string,
email: string,
age: number
}
type FormValidation = {
[key in keyof FormValues]: (value: FormValues[key]) => string | null;
}
const validate: FormValidation = {
name: (value: FormValues['name']) => value !== "" || 'This field is required',
email: (value: FormValues['email']) => value !== "" || 'This field is required',
age: (value: FormValues['age']) => value < 21 || 'Age must be above 21',
}
Now that we're typing the properties of the validate
object dynamically, each property must match a property key on FormValues
and the value passed to the function must match the type of the passed property.