简体   繁体   中英

Typescript Type of JSON schema object

Is there a special type associated with JSON-schema objects in typescript? My class has a method that checks whether its members satisfy the dynamic json schema schema , for now I do it like so,

<!-- language: typescript -->

verifySchema(schema: object): void {
    // do verification
}

where for example

<!-- language: typescript -->

const schema = {
  title: 'blabla',
  description: 'Basic schema',
  type: 'object',
  properties: {
    "firstName": {
    "type": "string",
    "description": "The person's first name."
    },
    "lastName": {
    "type": "string",
    "description": "The person's last name."
    },
...
}

But to remain generic I would like to allow for checking arbitrary json schemas, not just this specific one. Is it okay to set schema: object or are there best practices for JSON-schema objects?

You can use @types/json-schema .

Then:

import {JSONSchema7} from 'json-schema';

verifySchema(schema: JSONSchema7): void {
    // do verification
}

I needed to type a schema in the same way, but ideally I wanted a generic solution without an external package if possible, which allowed me to generically type the key based on a schema that can change and introduce additional property items.

I did this by adding a key index signature onto the interface meaning the key can be any string , but also typing additional properties for that string in this example this is type and description giving me the benefit of the key being generic but the keys properties are strictly typed.

export interface Schema {
  title: string;
  description: string;
  properties: Properties;
}

export interface Properties {
  [key: string]: {
    type: string;
    description: string;
  };
}

Schema can be initialised as

  const schema: Schema = {
    title: '',
    description: '',
    properties: {
      firstName: {
      description: '',
      type: '',
     },
     lastName: {
     description: '',
     type: '',
  },
 },
};

You can then access properties in the schema by its key and also benefit from intellisense suggestions, this can also be extended to support JSON $refs and required schema items.

const firstNameDescription = schema.properties.firstName.description;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM