'Validating enums with AJV in Typescript

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source