yup验证了打字稿中的枚举数组

发布于 2025-02-04 18:55:26 字数 922 浏览 3 评论 0原文

我正在尝试使用YUP来验证DTO的验证,但无法通过检查枚举解决一个问题。我有一个与下面类似的代码:

export enum TestEnum {
  TEST = 0,
  NOT_TEST = 1,
}

export interface SampleDTO {
  testEnum: TestEnum[];
}

export const sampleDtoSchema: SchemaOf<SampleDTO> = yup.object({
  testEnum: yup
    .array(
      yup
        .mixed<TestEnum>()
        .oneOf(Object.values(TestEnum) as TestEnum[])
        .required(),
    )
    .ensure(),
});

我会收到此错误:

Type 'MixedSchema<TestEnum | undefined, AnyObject, TestEnum>' is not assignable to type 'BaseSchema<Maybe<TestEnum.NOT_TEST>, AnyObject, TestEnum.NOT_TEST>'.
          Types of property '__inputType' are incompatible.
            Type 'TestEnum | undefined' is not assignable to type 'Maybe<TestEnum.NOT_TEST>'.
              Type 'TestEnum.TEST' is not assignable to type 'Maybe<TestEnum.NOT_TEST>'

应该如何正确完成它?

I am trying to validate DTO's using Yup and i can't resolve an issue with checking enums. I have a code similar to the one below:

export enum TestEnum {
  TEST = 0,
  NOT_TEST = 1,
}

export interface SampleDTO {
  testEnum: TestEnum[];
}

export const sampleDtoSchema: SchemaOf<SampleDTO> = yup.object({
  testEnum: yup
    .array(
      yup
        .mixed<TestEnum>()
        .oneOf(Object.values(TestEnum) as TestEnum[])
        .required(),
    )
    .ensure(),
});

And i get this error:

Type 'MixedSchema<TestEnum | undefined, AnyObject, TestEnum>' is not assignable to type 'BaseSchema<Maybe<TestEnum.NOT_TEST>, AnyObject, TestEnum.NOT_TEST>'.
          Types of property '__inputType' are incompatible.
            Type 'TestEnum | undefined' is not assignable to type 'Maybe<TestEnum.NOT_TEST>'.
              Type 'TestEnum.TEST' is not assignable to type 'Maybe<TestEnum.NOT_TEST>'

How it should be done correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜唯美灬不弃 2025-02-11 18:55:26

这可能会有所帮助:

export const sampleDtoSchema: yup.SchemaOf<SampleDTO> = yup.object({
  testEnum: yup
    .array(
      yup
        .mixed()
        .oneOf<TestEnum>(Object.values(TestEnum) as TestEnum[])
        .required()
    )
    .min(1)
    .ensure()
});

This might be helpful:

export const sampleDtoSchema: yup.SchemaOf<SampleDTO> = yup.object({
  testEnum: yup
    .array(
      yup
        .mixed()
        .oneOf<TestEnum>(Object.values(TestEnum) as TestEnum[])
        .required()
    )
    .min(1)
    .ensure()
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文