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

Issue

The two variants of my JSON response are:

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

and

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

Even though defined JSON Schema as:

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

Response Object:

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

getting an error as:

requires property “firstName”
requires property “LastName”
requires property “Address”

using “jsonschema” Node package.

Solution

First: Use proper type names in your schema (strings)

You want to write a JSON schema. According to the definition, your type can either be a string or an array of strings. What you do is pass a TypeScript type definition in, not a string.

Try

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

Second: undefined is not a valid type for a JSON schema

Having a property set to undefined is counted as that property not being set. I’d suggest you move to null for cases like that.

Answered By – fjc

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.