my-json-to-ts

1.0.2 • Public • Published

一、实现的功能

  • 将 JSON 数据转换为 TypeScript 类型定义。
  • 支持嵌套的复杂类型,如数组和对象。
  • 支持自定义类型名称和命名空间。
  • 支持将转换后的 TypeScript 类型定义保存为文件。

二、工具使用方法

  1. 安装工具:
npm install -g my-json-to-ts

  1. 运行工具:
my-json-to-ts input.json output.ts

其中 input.json 是要转换的 JSON 文件路径, output.ts 是转换后的 TypeScript 文件路径。

  1. 可选参数:
--name 类型名称    # 指定转换后的类型名称,默认为 JsonType
--namespace 命名空间 # 指定转换后的命名空间,默认为无
--no-file          # 不将转换后的 TypeScript 类型定义保存为文件

三、使用示例

以下是一个 JSON 数据和转换后的 TypeScript 类型定义示例:

🚲简单的JSON 数据

{
  "name": "John",
  "age": 30,
  "address": {
    "city": "New York",
    "state": "NY"
  },
  "hobbies": [
    "reading",
    "traveling"
  ]
}

🚲输出对应类型定义

interface JsonType {
  name: string;
  age: number;
  address: {
    city: string;
    state: string;
  };
  hobbies: string[];
}

复杂的JSON 数据

{
  "name": "John",
  "age": 30,
  "address": {
    "city": "New York",
    "state": "NY",
    "postalCode": 10001
  },
  "friends": [
    {
      "name": "Jane",
      "age": 28,
      "address": {
        "city": "Los Angeles",
        "state": "CA"
      }
    },
    {
      "name": "Bob",
      "age": 35,
      "address": {
        "city": "Chicago",
        "state": "IL"
      }
    }
  ],
  "hobbies": [
    "reading",
    "traveling",
    {
      "name": "swimming",
      "location": "pool"
    }
  ]
}

输出对应类型定义

interface JsonType {
  name: string;
  age: number;
  address: {
    city: string;
    state: string;
    postalCode: number;
  };
  friends: {
    name: string;
    age: number;
    address: {
      city: string;
      state: string;
    };
  }[];
  hobbies: (string | {
    name: string;
    location: string;
  })[];
}

Readme

Keywords

Package Sidebar

Install

npm i my-json-to-ts

Weekly Downloads

4

Version

1.0.2

License

ISC

Unpacked Size

5.45 kB

Total Files

3

Last publish

Collaborators

  • foxyuan