I’m using Yup validation in a React Typescript application. Based on the validation schema, how can I determine if a particular field is required? (I’m creating a custom text field component, and I want to dynamically add a required
property if the field is required in the schema.)
Right now, I have:
import * as yup from 'yup';
const schema = yup.object().shape({
name: yup.string().required('Required'),
email: yup.string(),
});
const isNameRequired = schema.fields['name'].spec?.presence === 'required';
The problem is – I’m getting the following Typescript error on spec
:
Property 'spec' does not exist on type 'Reference<unknown> | ISchema<string, AnyObject, any, any>'.
Property 'spec' does not exist on type 'Reference<unknown>'.ts(2339)
2
Answers
I ended up using a solution similar to this answer, but then simply cast a few of the variables as
any
(with an added/* eslint-disable @typescript-eslint/no-explicit-any */
at the top of the file). No matter what I tried casting to the "proper" way, it always ended up with another error, so I just decided it's not worth the headache, and that this should cause absolutely no issues, so I've proceeded using the following code with a clear conscience:You can use something like this .describe()