我很难为yup模式(https://github.com/jquense/yup/blob/master/docs/typescript.md)创建一个类型记录界面
给定类型记录界面:
interface TestInterface {
name: string;
};以下返回类型是有效的:
const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
name: Yup.string().required()
});但是在我的代码中,我使用了Yup.lazy(),但我无法找到应该如何为以下内容创建接口:
const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
name: Yup.lazy(() => Yup.string().required())
});我得到的错误是:
Type 'ObjectSchema<Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>, Record<...>, TypeOfShape<...>, AssertsShape<...>>' is not assignable to type 'ObjectSchemaOf<TestInterface>'.
Type 'Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>' is not assignable to type '{ name: BaseSchema<string, AnyObject, string>; }'.
Types of property 'name' are incompatible.
Type 'Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>' is missing the following properties from type 'BaseSchema<string, AnyObject, string>': deps, tests, transforms, conditions, and 35 more.ts(2322)发布于 2022-03-10 08:34:57
您的示例的工作原理是您希望使用Yup.ObjectSchema并添加要求您的对象。
一定要将.required()添加到.shape或.object链中,这样模式的字段就一定会从类型记录的角度存在。它实质上是充当NonNullable<TestInterface>的角色。
// ✅ happy type
const testSchema1: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
name: Yup.string().required(),
}).required();
// ✅ happy type
const testSchema2: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
name: Yup.lazy(() => Yup.string().required())
}).required();注意事项:使用当前版本(截至本文) 0.32.11。在普通JS中有一个带有存根类型的runkit示例可以看到[这里]
资料来源:https://github.com/jquense/yup/#ensuring-a-schema-matches-an-existing-type
https://stackoverflow.com/questions/68347196
复制相似问题