Typescript JSON架构对象的类型

q3qa4bjr  于 2023-02-01  发布在  TypeScript
关注(0)|答案(2)|浏览(173)

在typescript中有没有一个特殊的类型与JSON模式对象相关联?我的类有一个方法可以检查它的成员是否满足动态JSON模式schema,现在我是这样做的,

<!-- language: typescript -->

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

其中例如

<!-- 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."
    },
...
}

但是为了保持通用性,我希望允许检查任意的json模式,而不仅仅是这个特定的模式。设置schema: object是否合适,或者是否有针对JSON模式对象的最佳实践?

inkz8wg9

inkz8wg91#

您可以使用@types/json-schema。
然后:

import {JSONSchema7} from 'json-schema';

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

wj8zmpe12#

我需要以相同的方式输入模式,但理想情况下,我希望有一个通用的解决方案,如果可能的话,不需要外部包,这样我就可以基于一个可以更改和引入附加属性项的模式来通用地输入键。
我通过在接口上添加一个键索引签名来实现这一点,这意味着键可以是任何string,但也为该string键入了其他属性,在本例中,这是typedescription,这给我带来了键是通用的好处,但键属性是严格类型化的。

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

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

架构可初始化为

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

然后,您可以通过键访问模式中的属性,还可以从智能感知建议中受益,这还可以扩展为支持JSON $refsrequired模式项。

const firstNameDescription = schema.properties.firstName.description;

相关问题