JsonSchema 转换为 Typescript

前因

前端使用了 Typescript 每次对接 接口的时候都需要耗费时间写类型 。如何提高生产力呢?工具去处理重复性的工作。 下面我们就来实现这个需求。
**已知 接口工具可以将参数导出成 JsonSchema **

输入:JsonSchema数据格式

{
  title: "返回数据",
  type: ["array", "null"],
  items: {
    type: "object",
    properties: {
      id: {
        type: "number",
      },
      title: {
        type: "string",
      },
    },
    required: ["id", "title"],
  },
}

输出:Ts 类型

type ResponseData = {
  id : number
  title : string
}[]|null

**JsonSchema **知己知彼

  • $schema:用于指定JSONSchema的版本信息,该值由官方提供,不可乱写。该关键字可以省略。
  • title:当前schema的标题信息。可以省略
  • description:当前节点的描述
  • type:当前节点的类型,最外层type代表json的最外层是什么样的类型。例如上方的例子中,符合该JsonSchema的json数据必需是一个JsonObject而不能是一个JsonArray
  • properties:代表当前节点的子节点信息。
  • required: 是一个数组类型,代表当前节点下必需的节点key。例如上方例子中,规定了json的格式必需要有id和title节点。

其他的大家就面向Search Engines编程吧

代码实现

const typeMap = {
  integer: "number",
};
// JsonSchema转TS类型
const jsonschema2TsType = (obj) => {
  if (obj.type instanceof Array) {
    return obj.type
      .map((item) =>
        jsonschema2TsType({
          ...obj,
          type: item,
        })
      )
      .join("|");
  } else {
    switch (obj.type) {
      case "object":
        let str = "{\n";
        for (let key in obj.properties) {
          const item = obj.properties[key];
          // description
          if (item.title || item.description) {
            str += `/** ${item?.title ?? ""}${item?.description ?? ""} */\n`;
          }
          // required
          const isRequired = obj.required && obj.required.includes(key);
          str += `${key}${isRequired ? "" : "?"}:${jsonschema2TsType(item)}\n`;
        }
        str += "\n}";
        return str;
      case "array":
        return `${jsonschema2TsType(obj.items)}[]`;
      default:
        return typeMap[obj.type] ?? obj.type;
    }
  }
};

const json = {
  title: "返回数据",
  type: ["array", "null"],
  items: {
    type: "object",
    properties: {
      id: {
        type: "number",
      },
      title: {
        type: "string",
      },
    },
    required: ["id", "title"],
  },
};

console.log(`type ResponseData = ${jsonschema2TsType(json)}`);

输出结果

type ResponseData = {
id:number
title:string

}[]|null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Here is a possible JSON schema for the TypeScript compiler's configuration file: ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "TypeScript Compiler Configuration", "type": "object", "properties": { "compilerOptions": { "type": "object", "properties": { "allowJs": { "type": "boolean" }, "checkJs": { "type": "boolean" }, "noEmit": { "type": "boolean" }, "noEmitOnError": { "type": "boolean" }, "strict": { "type": "boolean" }, "target": { "type": ["string", "number"], "enum": ["ES3", "ES5", "ES6", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ESNext"] }, "module": { "type": ["string", "number"], "enum": ["CommonJS", "AMD", "System", "UMD", "ES6", "ES2015", "ES2020", "ESNext"] }, "outFile": { "type": "string" }, "outDir": { "type": "string" }, "rootDir": { "type": "string" }, "baseUrl": { "type": "string" }, "paths": { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "string" } } }, "typeRoots": { "type": "array", "items": { "type": "string" } }, "types": { "type": "array", "items": { "type": "string" } }, "lib": { "type": "array", "items": { "type": "string" } }, "experimentalDecorators": { "type": "boolean" }, "emitDecoratorMetadata": { "type": "boolean" } }, "additionalProperties": false }, "include": { "type": "array", "items": { "type": "string" } }, "exclude": { "type": "array", "items": { "type": "string" } } }, "required": ["compilerOptions"], "additionalProperties": false } ``` This schema defines an object with three properties: `compilerOptions`, `include`, and `exclude`. The `compilerOptions` property is itself an object with various properties for configuring the TypeScript compiler, such as `allowJs`, `checkJs`, `noEmit`, `strict`, etc. The other two properties, `include` and `exclude`, are arrays of file patterns to include or exclude from compilation. The schema includes type validations and some additional constraints, such as allowed values for `target` and `module`.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵忠洋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值