用TypeScript中的AJV验证枚举

发布于 2025-01-28 19:30:24 字数 687 浏览 4 评论 0原文

假设我有一个类似的接口和架构:

enum FooEnum {
  Bar = 'BAR',
}

interface Foo {
  enumValue: FooEnum.Bar
}

const schema = JSONSchemaType<Foo> = {
  type: 'object',
  properties: {
    enumValue: {
      const: Foo[FooEnum.Bar]
    }
  }
}

这将失败,因为打字稿会抱怨这些类型不是相同的类型。

两个(相关的)问题:

  1. 如何在模式中使用具有const值的AJV和打字稿?即使用字符串文字替换了枚举,Typescript也会抱怨(请参阅: htttps:htttps:// github。 com/ajv-validator/ajv/essess/1984

  2. ajv解析输入枚举值作为他们应该出现的实际枚举类型吗?如果是这样,我该如何设置该行为?

Say I have an interface and schema like so:

enum FooEnum {
  Bar = 'BAR',
}

interface Foo {
  enumValue: FooEnum.Bar
}

const schema = JSONSchemaType<Foo> = {
  type: 'object',
  properties: {
    enumValue: {
      const: Foo[FooEnum.Bar]
    }
  }
}

This will fail because typescript will complain that these are not the same type.

Two (related) questions:

  1. how can I use AJV and Typescript with const values in the schema? Typescript complains even if the enum was replaced with string literals (see: https://github.com/ajv-validator/ajv/issues/1984)

  2. can AJV parse input enum values as the actual enum types that they are supposed to come out as? If so, how do I set that behavior?

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

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

发布评论

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

评论(1

や三分注定 2025-02-04 19:30:24

第一个问题的答案最终变得很简单:我需要给jsonschema中的const值提供类型。

constantValue: { type: 'string', const: 'FOO' }

第二个似乎是不可能的。

The answer to the first question ended up being straightforward: I needed to give a type for the const value in the jsonschema.

constantValue: { type: 'string', const: 'FOO' }

The second seems like its not possible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文