Skip to content

Presence of default value for an object property should not imply required. #211

@nhollander-alert

Description

@nhollander-alert

According to the json schema specification, the default keyword is a meta-data annotation for "documentation and user interface display purposes" 1. The schema reference states that "...default is typically used to express that if a value is missing, then the value is semantically the same as if the value was present with the default value." 2

Based on this, I would expect that the default value would be entirely ignored by this library, as it is a purely semantic marker which tells users that an undefined value will be treated by the tool as if it were the given value, but there is no requirement that processing tools substitute undefined for the default value.

Given the following schema definition this library correctly produces an object where foo is required but bar is optional.

type test = FromSchema<{
    type: "object",
    additionalProperties: false,
    required: ["foo"],
    properties: {
        foo: { type: "string" },
        bar: { type: "string" }
    }
}>;
type test = {
    bar?: string | undefined;
    foo: string;
}

If we alter bar to include a default value, the resulting type no longer accepts undefined as a valid value, despite it still being an allowed value per the spec.

type test = FromSchema<{
    type: "object",
    additionalProperties: false,
    required: ["foo"],
    properties: {
        foo: { type: "string" },
        bar: { type: "string", default: "abcd" }
    }
}>;
type test = {
    foo: string;
    bar: string;
}

Footnotes

  1. https://json-schema.org/draft/2020-12/json-schema-validation#section-9.2

  2. https://json-schema.org/understanding-json-schema/reference/annotations

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