Skip to content

typescript 生成 json-schema 命令

利用 json-schema 可以让普通 json、yaml 配置文件,拥有格式效验和智能提示

json 和 yaml 文件都可以使用

安装 typescript-json-schema 可将 ts 定义导出为 json-schema 文件

bash
npm i -g typescript-json-schema
typescript-json-schema ./types.ts Person --required -o ./schema.json

代码演示

ts
type Sex = 'male' | 'female';

export interface Person {
  name: string;
  age: number;
  sex: Sex;
  hobbies: string[];
  children?: Person[];
}
json
{
  "$ref": "#/definitions/Person",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Person": {
      "properties": {
        "age": {
          "type": "number"
        },
        "children": {
          "items": {
            "$ref": "#/definitions/Person"
          },
          "type": "array"
        },
        "hobbies": {
          "items": {
            "type": "string"
          },
          "type": "array"
        },
        "name": {
          "type": "string"
        },
        "sex": {
          "$ref": "#/definitions/Sex"
        }
      },
      "required": ["age", "hobbies", "name", "sex"],
      "type": "object"
    },
    "Sex": {
      "enum": ["female", "male"],
      "type": "string"
    }
  }
}
json
{
  "$schema": "./schema.json",
  "name": "11",
  "sex": "1"
}
// 此时控制台出现错误警告
// 缺少属性 "age"。 [行 1,列 1]
// 缺少属性 "hobbies"。[行 1,列 1]
// 值不被接受。有效值: "female", "male"。(1) [行 4,列 10]

这个网站里有常见的 schema 配置文件

https://www.schemastore.org/json/

示例 json

json
{
  "$schema": "https://json.schemastore.org/nodemon.json",
  "verbose": true,
  "ignore": ["*.test.js", "fixtures/*"],
  "execMap": {
    "rb": "ruby",
    "pde": "processing --sketch={{pwd}} --run"
  }
}

示例 yaml (github ci)

vscode 需要安装插件 yaml 来支持 yaml 文件

yaml
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: release
on:
  push:
    branches:
      - master
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout 🛎️
        uses: actions/checkout@v2.3.1

      - name: Cache Modules 📦
        uses: actions/cache@v2
        env:
          cache-name: cache-node-modules
        with:
          path: |
            ~/.pnpm-store
            ~/.npm
            ./node_modules
          key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('./pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-build-${{ env.cache-name }}-
            ${{ runner.os }}-build-
            ${{ runner.os }}-

      - name: Install Packages 🔧
        run: npm i -g pnpm && pnpm i

      - name: Build 🔧
        run: npm run build

      - name: Deploy 🚀
        uses: JamesIves/github-pages-deploy-action@4.1.4
        with:
          branch: script # The branch the action should deploy to.
          folder: dist # The folder the action should deploy.