log("Data is invalid: ", validate.errors); } 注意:这里的User应该是你通过typescript-json-schema库转换得到的JSON Schema对象,而不是TypeScript接口。 总结 通过以上步骤,你可以使用TypeScript结合JSON Schema来校验JSON文件格式。这种方法的好处是可以利用TypeScript的类型系统来定义期望的JSON结构,并通过JSON ...
},"required": ["id","token"],"type":"object"} } } 4、封装一个校验方法 // validate.tsimportAjvfrom'ajv';importschemafrom'.tsJsonSchema.json';constajv =newAjv({schemas: [schema] });exportfunctionvalidateDataByType(type:string, data: unknown) {console.log(`开始校验,类型:${type}, 数...
console.log(v.validate(instance, schema)); 现在可以根据 JSON Schema 去校验后端返回数据的格式是否正确了,但是为每个接口手动编写 JSON Schema 是不现实的,我们自然会想到能不能将 TypeScript 的接口类型定义转为 JSON Schema? TypeScript Interface -> JSON Schema 好在已经有typescript-json-schema这个库帮我们...
type MyType = { name: string; description: string; } // Validate this value with a custom type guard (extend to your needs) function isMyType(o: any): o is MyType { return "name" in o && "description" in o } const json = '{ "name": "Foo", "description": "Bar" }'; con...
[ ]validateRequired(eg) [x] literal objects in enum (eg) [x] referencing schema by id (eg) [x] custom typescript types viatsType Custom schema properties: tsType: Overrides the type that's generated from the schema. Useful for forcing a type toanyor when using non-standard JSON schema...
if (validate.errors) { // do something }优点:JTD 支持从已有的schema提取TS类型,避免维护两...
有了JSON Schema,怎么使用它校验 JSON 对象的合法性呢?这里就用到了刚刚提到的jsonschema 库。简单使用示例如下: varValidator = require('jsonschema').Validator;varv =newValidator();varinstance =4;varschema= {"type":"number"};console.log(v.validate(instance,schema)); ...
基于TypeScript代码生成JSON Schema -- 比如typescript-json-schema这个工具就可以做到这一点(同时支持作为命令行工具使用和通过代码调用)。 -- 需要确保 Schema 和代码同步更新。 基于JSON 输入示例生成 -- 没有使用已经在 TypeScript 代码中定义的类型信息。
<input disabled="" type="checkbox">validateRequired(eg) <input checked="" disabled="" type="checkbox"> literal objects in enum (eg) <input checked="" disabled="" type="checkbox"> referencing schema by id (eg) <input checked="" disabled="" type="checkbox"> custom typescript types via...
validateRequired (eg) literal objects in enum (eg) referencing schema by id (eg) custom typescript types via tsTypeCustom schema properties:tsType: Overrides the type that's generated from the schema. Useful for forcing a type to any or when using non-standard JSON schema extensions (eg)....