我将阅读应该格式正确的用户输入对象。
也就是说,输入对象现在可以具有未在界面中定义的任何键或子结构。
如果用户提供无效对象,我怎么能抛出异常?
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_TYPO
,nameTHIS_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"
}
]
}
]
}
答案 0 :(得分:5)
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