在 yup 模式中使用 typescript 类型

Rem*_*emi 5 typescript yup

可以在 yup 验证中使用打字稿类型吗?

是的,您可以:

yup.string().oneOf(['salami', 'tuna', 'cheese']);
Run Code Online (Sandbox Code Playgroud)

在我的一个组件中,我定义了这种类型:

type toppings = 'salami' | 'tuna' | 'cheese';
Run Code Online (Sandbox Code Playgroud)

我可以将这两者结合起来吗?IE:

type toppings = 'salami' | 'tuna' | 'cheese';
yup.string().oneOf(toppings); // <- how?
Run Code Online (Sandbox Code Playgroud)

cas*_*hol 10

为了在 @Vencovsky 的答案的基础上构建一点,如果您想避免将类型转换为枚举,可以使用 const 断言。

const possibleToppings = ['salami', 'tuna', 'cheese'] as const;

type toppings = typeof possibleToppings[number]; // 'salami' | 'tuna' | 'cheese'

yup.mixed<toppings>().oneOf([...possibleToppings]);
Run Code Online (Sandbox Code Playgroud)


Ven*_*sky 5

您可以使用yup.mixed<TYPE>()传递泛型类型。

yup.mixed<toppings>().oneOf(['salami', 'tuna', 'cheese']);
Run Code Online (Sandbox Code Playgroud)

您将其作为 传递yup.string(),但它不是字符串,而是 的类型'salami' | 'tuna' | 'cheese',其中包含字符串但不是任何字符串,因此您需要使用.mixed来定义特定值。

如果你不想直接传递与类型值的数组,你可以看看这个问题上如何做到这一点。