gpt4 book ai didi

javascript - 如果对象结构不匹配/不适合另一个对象结构,如何抛出异常

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:59 24 4
gpt4 key购买 nike

我将读取格式正确的用户输入对象。

也就是说,输入对象现在可以具有接口(interface)中未定义的任何键或子结构。

如果用户提供了无效对象,我如何抛出异常?

预定义接口(interface)

  export interface InputStructureInterface {
"tableName": string,
"viewType": string,
"structureName": string,
"sections": Array<Section>,
}

interface Section{
"name": string,
"fields": Array<Field>
}

interface Field{
"fieldName": string,
"relationType": string,
"relationName": null,
"fieldUi": FieldUi
}

interface FieldUi {
"fieldType": string,
"label": strin
}

有效的输入结构

这个结构是定义的InputStructureInterface下的一个子集

  {
"tableName": "User",
"viewType": "List View",
"structureName": "personal_data_settings_list_view",
"sections": [
{
"name": null,
"fields": [
{
"fieldName": "Name",
"relationType": null,
"relationName": null,
"fieldUi": {
"fieldType": "string",
"label": "Name"
},
}
]
}
]
}

输入结构无效

因为 viewTypeTHIS_IS_A_TYPOnameTHIS_IS_A_TYPO 没有出现在界面上

{
"tableName": "User",
"viewTypeTHIS_IS_A_TYPO": "List View",
"structureName": "personal_data_settings_list_view",
"sections": [
{
"nameTHIS_IS_A_TYPO": null,
"fields": [
{
"fieldNameTHIS_IS_A_TYPO": "Name"
}
]
}
]
}

最佳答案

TypeScript 只会在编译时强制执行类型。如果你想进行这种验证,你需要使用某种 json-schema 验证库。例如:https://github.com/epoberezkin/ajv

更新

例如,使用这个库 ( https://github.com/epoberezkin/ajv ) 你可以做这样的事情:

import * as Ajv from 'ajv';
const ajv = new Ajv();

const schema = {
"type": "object",
"properties": {
"tableName": { "type": "string" },
"viewType": { "type": "string" },
"structureName": { "type": "string" },
"sections": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"name": { "type": ["string", "null"] },
"fields": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"fieldName": { "type": "string" },
"relationType": { "type": ["string", "null"] },
"relationName": { "type": ["string", "null"] },
"fieldUi": {
"fieldType": { "type": "string" },
"label": { "type": "string" }
}
},
"required": ["fieldName", "relationType", "relationName"],
"additionalProperties": false
}
]
}
},
"required": ["name", "fields"],
"additionalProperties": false
}
]
}
},
"required": ["tableName", "viewType", "structureName"],
"additionalProperties": false
};

const validate = ajv.compile(schema);
let valid = validate(data); // <-- pass your json object here

if (!valid) {
console.log(validate.errors);
}

安装库:npm install ajv

关于javascript - 如果对象结构不匹配/不适合另一个对象结构,如何抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com