typescript-json-schema
typescript-json-schema copied to clipboard
If / Then / Else support?
Do you have AJV if/then/else support? I didn't see it in the docs. That would be great for validating properties that have relationships.
How would you represent this feature of JSON Schema with Typescript interfaces? The closest thing that comes to my mind are Typescripts Conditional Types but they don't seem to fit the if / then / else construct of JSON Schema.
I would just use the decorator. There's a lot of flexibility in the if/then/else schema.
The JSON Schema example of
{
"if": { "properties": { "power": { "minimum": 9000 } } },
"then": { "required": [ "disbelief" ] },
"else": { "required": [ "confidence" ] }
}
I assume could look like this:
/**
* @if properties.power.minimum 9000
* @then required disbelief
* @else required confidence
**/
interface Something {
power: number;
disbelief?: string;
confidence?: string;
}
Turns out I would need conditional support as well. Is there any work around for cases where this library can't cover? Or would I just have to write a post processing script to add it after the schema is generated.
the same issue! any ideas?
Seems like we still don't have a solution! :(
you can use this type definition to instead IF/Then/Else
export type Test = {
enable: false
} | {
enable: true
requiredValue: string
requiredObj: {
hello: string
}
}
export interface Config {
test: Test
}
generated json schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Test": {
"anyOf": [
{
"properties": {
"enable": {
"const": false,
"type": "boolean"
}
},
"required": [
"enable"
],
"type": "object"
},
{
"properties": {
"enable": {
"const": true,
"type": "boolean"
},
"requiredObj": {
"properties": {
"hello": {
"type": "string"
}
},
"required": [
"hello"
],
"type": "object"
},
"requiredValue": {
"type": "string"
}
},
"required": [
"enable",
"requiredObj",
"requiredValue"
],
"type": "object"
}
]
}
},
"properties": {
"test": {
"$ref": "#/definitions/Test"
}
},
"required": [
"test"
],
"type": "object"
}
example:
// ok
{
"test": {
"enable": false
}
}
// error: Required properties are missing from object: requiredObj, requiredValue.
{
"test": {
"enable": true
}
}