I have a field in my JSON that is supposed to hold the allowed values for a dropdown input.
[
{
"field": "status",
"type": "select",
"defaultValue": "open",
"allowedValues": ["open", "pending", "closed"]
},
...
]
This field must contain an array of strings or a token name (e.g. $allowedValues$) from which my code must pull the list of allowed values.
My problem is that I would like to use Ajv to validate the JSON, but apparently type string and array are not allowed to be used together.
enum InputType {
SIMPLE = "simple",
SELECT = "select",
AUTOCOMPLETE = "autocomplete",
}
interface DefaultDefinition {
...
type: InputType;
allowedValues: string | string[];
}
const defaultDefinitionSchema: JSONSchemaType<DefaultDefinition> = {
type: "object",
properties: {
...
type: {
type: "string",
enum: [InputType.AUTOCOMPLETE, InputType.SELECT, InputType.SIMPLE],
},
allowedValues: {
type: ["array", "string"],
items: { type: "string" },
}
},
required: ["allowedValues"],
additionalProperties: false,
};
Error message
Types of property 'type' are incompatible. Type '("string" | "array")[]' is not assignable to type '"array"'.
As a workaround I have considered adding another property called allowedValuesToken of type string and making the allowedValues a string array.
The problem with this approach is, that one of those properties must be required, but never both.
I was wondering if I can specify this via if/then, but I already have a if/then condition (I could not test it yet, due to my issue with the type of allowedValues) and it seems that since I have to define the absolute list of required fields in then/else (contrary to dynamically adding/removing single fields) this is not really feasible way either.
if: {
properties: {
type: {
enum: [InputType.SIMPLE],
},
},
},
then: { required: ["type"] },
else: { required: ["type","allowedValues"] },
Can anyone tell me what is the proper way to it achieve my requirement?