Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use typescript type in yup schema

Tags:

typescript

yup

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?
like image 980
Remi Avatar asked Sep 24 '20 12:09

Remi


2 Answers

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.

like image 84
Vencovsky Avatar answered Oct 16 '22 16:10

Vencovsky


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]);
like image 4
caseyjhol Avatar answered Oct 16 '22 17:10

caseyjhol