create-validator-ts icon indicating copy to clipboard operation
create-validator-ts copied to clipboard

Support for JSDoc default values

Open loopingrage opened this issue 1 year ago • 1 comments

It would be awesome if one could annotate a field with JSDoc @default like this:

export type Config = BaseConfig & {
  sparkplug: {
    groupIds: string[]
    systemTopic: string
  }
  advanced?: {
    /**
     *  @default true
     */
    disableSomeFeature?: boolean
  }
}

And have the resulting validator JSON Schema include the default value. In this way, the validator could be also used to apply default values to user-provided JSON inputs.

Has this been considered? Would you consider this in scope for this library? If so, would you consider a PR with this feature?

loopingrage avatar Mar 25 '24 23:03 loopingrage

Generated JSON schema already supports @default. AJV ignores default property by default.

  • https://github.com/vega/ts-json-schema-generator/issues/249
  • https://ajv.js.org/options.html#usedefaults

If you use the useDefaults option using the Custom Validator, you can support the @default tag.

new Ajv({ removeAdditional: true, useDefaults: true });

Ajv has a variety of options, we need to consider how to support. (There should be users who want to use other than Ajv.)

  • Related: https://github.com/azu/create-validator-ts/issues/2

azu avatar Mar 25 '24 23:03 azu

https://github.com/azu/create-validator-ts/releases/tag/v6.0.0 support useDefault by default.

azu avatar Apr 13 '24 14:04 azu