【发布时间】:2020-07-28 04:11:30
【问题描述】:
我是 JSON 模式验证的新手,我正在为配置构建自定义模式。我正在构建的架构基于 Typescript 类型。我了解如何验证简单的数据类型,如数组、对象、数字、字符串等。
但是有没有办法像这样指定类型:
type Conf = {
idle_session_timeout?: number | "none",
item: {
kind: "attribute";
name: string;
} | {
kind: "relation";
name: string;
} | {
kind: "group";
name: string;
label?: string | undefined;
entries: PresentationItem[];
}
order_by: string | {
attribute: string;
direction?: "asc" | "desc" | undefined;
}
}
我从http://json-schema.org/draft-07/schema 注意到它支持 if then else 语句来根据值切换验证模式,但我不知道如何实现它们。
【问题讨论】:
-
对于复杂类型,
anyOf应该是您要查找的内容。对于像order_by.direction这样的简单枚举,enum可能会派上用场。 -
您不必从头开始编写这些模式。有用于从 Typescript 生成 JSON Schema 的现有包。您可能想查看其中的一个,并从它们产生的内容中学习,甚至只在之后通过标题和描述等来增强它们。
标签: jsonschema json-schema-validator