json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Add support for JSON Schema 7 if/then/else

Open williamrijksen opened this issue 3 years ago • 4 comments

When I copy the schema which is also on the JSON schemas documentation it's not recognizing the postal_code statements to be included.

It's just converting to the following, missing the postal_code.

export type Demo = {
  [k: string]: unknown;
} & {
  street_address?: string;
  country?: "United States of America" | "Canada" | "Netherlands";
  [k: string]: unknown;
};

How could we solve this issue?

{
  "type": "object",
  "properties": {
    "street_address": {
      "type": "string"
    },
    "country": {
      "default": "United States of America",
      "enum": ["United States of America", "Canada", "Netherlands"]
    }
  },
  "allOf": [
    {
      "if": {
        "properties": { "country": { "const": "United States of America" } }
      },
      "then": {
        "properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
      }
    },
    {
      "if": {
        "properties": { "country": { "const": "Canada" } },
        "required": ["country"]
      },
      "then": {
        "properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
      }
    },
    {
      "if": {
        "properties": { "country": { "const": "Netherlands" } },
        "required": ["country"]
      },
      "then": {
        "properties": { "postal_code": { "pattern": "[0-9]{4} [A-Z]{2}" } }
      }
    }
  ]
}

williamrijksen avatar Nov 29 '21 13:11 williamrijksen

I have the same problem, did you find a solution or workaround @williamrijksen ?

roydigerhund avatar Feb 07 '22 08:02 roydigerhund

if/then is not currently supported. Proposals welcome!

bcherny avatar May 22 '22 04:05 bcherny

if/then is not currently supported. Proposals welcome!

bcherny avatar May 22 '22 04:05 bcherny

I'd assume majority of usecases for these keywords are just variations of discriminated unions. The example in the OP basically has this type:

type Demo = {
  street_address?: string
  country?: "United States of America" | "Canada" | "Netherlands"
} & (
  {
    country: "United States of America"
    postal_code: string
  }
  | {
    country: "Canada"
    postal_code: string
  }
  | {
    country: "Netherlands"
    postal_code: string
  }
)

I'd say the schema in the OP isn't a good example for these keywords because it can be replaced by anyOf/oneOf discriminated union and will be more readable in the end, along with the clearer derived type. So I guess the real question are there uses for "if"/"then" which aren't just complicated discriminated unions?

GabenGar avatar Aug 30 '22 16:08 GabenGar