Can a typescript type be used in a yup validation?
In yup you can:
yup.string().oneOf(['salami', 'tuna', 'cheese']);
In one of my components I have this type defined:
type toppings = 'salami' | 'tuna' | 'cheese';
Can I combine these two? I.e.:
type toppings = 'salami' | 'tuna' | 'cheese';
yup.string().oneOf(toppings); // <- how?
                You can use yup.mixed<TYPE>() passing your generic type.
yup.mixed<toppings>().oneOf(['salami', 'tuna', 'cheese']);
You are passing it as yup.string(), but it isn't a string, it's the type of 'salami' | 'tuna' | 'cheese', which contain string but isn't any string, so you need to use .mixed to define a specific value.
If you don't want to pass directly the array with the type values, you can take a look at this question on how to make it.
To build on @Vencovsky's answer a bit, you can use a const assertion if you want to avoid converting the type to an enum.
const possibleToppings = ['salami', 'tuna', 'cheese'] as const;
type toppings = typeof possibleToppings[number]; // 'salami' | 'tuna' | 'cheese'
yup.mixed<toppings>().oneOf([...possibleToppings]);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With