Skip to content

Optional fields with default values are not considered as required if treatDefaultedOptionalAsRequired is set to true #490

@tyio

Description

@tyio

Describe the bug
It appears that the current implementation of the treatDefaultedOptionalAsRequired option in src/parse (Line 70) does not align with the documented behavior.

To Reproduce
Steps to reproduce the behavior:

// for the schema 
export const Schema = Joi.object({
  foo: Joi.number()
    .integer()
    .positive()
    .default(60000)
    .optional(),
});

// and configuration options
await convertFromDirectory({
      treatDefaultedOptionalAsRequired: true,
      ...
});

Expected behavior
The treatDefaultedOptionalAsRequired option should mark fields as required.

export interface Schema {
  foo: 60000 | number;
}

Actual behavior
Fields are still marked as optional.

export interface Schema {
  foo?: 60000 | number;
}

Additional context
The implementation can be updated:

if (
  presence === 'required' ||
  (settings.treatDefaultedOptionalAsRequired && presence === 'optional' && value !== undefined)
) {
  required = true;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions