首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >`Yup.lazy()的Yup和类型记录模式接口

`Yup.lazy()的Yup和类型记录模式接口
EN

Stack Overflow用户
提问于 2021-07-12 12:12:24
回答 1查看 4.6K关注 0票数 6

我很难为yup模式(https://github.com/jquense/yup/blob/master/docs/typescript.md)创建一个类型记录界面

给定类型记录界面:

代码语言:javascript
复制
interface TestInterface {
  name: string;
};

以下返回类型是有效的:

代码语言:javascript
复制
const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.string().required()
});

但是在我的代码中,我使用了Yup.lazy(),但我无法找到应该如何为以下内容创建接口:

代码语言:javascript
复制
const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.lazy(() => Yup.string().required())
});

我得到的错误是:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2022-03-10 08:34:57

您的示例的工作原理是您希望使用Yup.ObjectSchema并添加要求您的对象。

一定要将.required()添加到.shape.object链中,这样模式的字段就一定会从类型记录的角度存在。它实质上是充当NonNullable<TestInterface>的角色。

代码语言:javascript
复制
//    ✅ 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68347196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档