简体   繁体   中英

Use typescript type in yup schema

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? Ie:

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' 'salami' | 'tuna' | 'cheese' '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]);

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