json-schema-to-typescript
json-schema-to-typescript copied to clipboard
Add support for JSON Schema 7 if/then/else
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}" } }
}
}
]
}
I have the same problem, did you find a solution or workaround @williamrijksen ?
if/then is not currently supported. Proposals welcome!
if/then is not currently supported. Proposals welcome!
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?