如何验证 return 类型字符串的 JSON 模式|使用打字稿未定义

how to validate JSON schema of return type String| undefined using typescript

我的 JSON 回复的两个变体是:

{
  firstName: "abc",
  LastName: "xyz",
  Address: "abc123"
}

{
  firstName: undefined,
  LastName: undefined,
  Address: undefined
}

即使将 JSON 架构定义为:

var ResponseSchema = {
  "firstName": {
    "type": [String,undefined],
  },
  "LastName": {
    "type": [String,undefined],
  },
  "Address": {
    "type": [String,undefined],
  },
  "required": [
    "firstName",
    "LastName",
    "Address",
  ],
}

响应对象:

{
  firstName: undefined,
  LastName: undefined,
  Address: undefined
}

出现错误:

需要属性"firstName"
需要 属性 "LastName"
需要 属性 "Address"

使用 "jsonschema" 节点包。

我不知道 jsonschema,但你的定义和必填字段对我来说看起来有些概念性错误。

你定义

"required": [
  "firstName", 
  "LastName", 
  "Address"
]

但将每个字段的类型设置为 String,undefined。如果您现在将它们设置为 undefined,则不满足要求。

换句话说:jsonschema 似乎有效,因为它会为您的响应抛出该错误:

{
  "firstname": undefined,
  "Lastname": undefined,
  "Address": undefined,
}

null 在 JSON 中是有效类型,在 JSON Schema.

中也是如此

我不懂打字稿,但这里有一个 JSON 架构作为示例。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "properties": {
    "a": {
      "type": [
        "string",
        "null"
      ]
    }
  },
  "required": [
    "a"
  ]
}

作为实例 JSON,这将通过验证:

{
  "a": null
}

首先:在您的模式(字符串)中使用正确的类型名称

您想编写一个 JSON 架构。根据定义,您的 type 可以是字符串或字符串数​​组。你所做的是传递 TypeScript 类型定义,而不是字符串。

尝试

  "firstName": {
    "type": ["string", "null"],
  },
  "LastName": {
    "type": ["string", "null"],
  },
  "Address": {
    "type": ["string","null"],
  },
  "required": [
    "firstName",
    "LastName",
    "Address",
  ]

其次:undefined 不是 JSON 模式的有效类型

将 属性 设置为 undefined 被视为未设置 属性。对于这种情况,我建议您转到 null