JSPM

  • Created
  • Published
  • Downloads 1444
  • Score
    100M100P100Q104195F
  • License MIT

JSON 智能生成 TypeScript 类型定义 - 一键从 JSON 数据生成 Interface / Type 定义

Package Exports

  • type-flash
  • type-flash/dist/index.js
  • type-flash/dist/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (type-flash) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

type-flash

JSON 智能生成 TypeScript 类型定义

npm version license

One line of code, types generated instantly. 一行代码,类型秒出。告别手写 Interface 的繁琐时代。

功能特性快速开始使用方式配置选项对比优势


✨ 功能特性

🎯 核心能力

  • 🔍 智能类型推断 - 自动识别 string / number / boolean / null / undefined 等基础类型
  • 📦 嵌套对象支持 - 递归遍历深层结构,自动生成子接口定义
  • 🔗 联合类型推断 - 数组元素类型不同?自动合并为 (string | number)[]
  • ❓ 可选属性识别 - 数组中部分对象缺少某字段?自动标记为 ? 可选
  • 🔄 结构等价去重 - 相同结构的对象复用同一类型,避免重复定义
  • 🔁 循环引用检测 - 智能检测并处理 JSON 中的循环引用

⚡ 增强功能

  • 🧬 泛型模式识别 - 智能识别分页结构 { list: T[], total: number },提取为 PageResult<T>
  • 📝 JSDoc 注释生成 - 根据字段名猜测含义,自动生成文档注释
  • 🎨 多种输出风格 - 支持 interfacetype alias 两种输出风格
  • 📏 灵活命名控制 - 支持 PascalCase / camelCase、前缀后缀、自定义类型名映射

🛠️ 工程化支持

  • 💻 CLI 命令行工具 - 开箱即用的命令行工具,支持管道输入
  • 📦 双模块输出 - 同时提供 CommonJS 和 ESM 两种模块格式
  • 🔩 TypeScript 原生 - 纯 TypeScript 编写,类型定义开箱即用

🚀 快速开始

安装

# npm
npm install type-flash --save-dev

# yarn
yarn add type-flash -D

# pnpm
pnpm add type-flash -D

一行代码上手

import { generate } from 'type-flash';

const jsonData = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  profile: {
    avatar: 'https://example.com/avatar.jpg',
    bio: 'Hello World',
  },
  tags: ['admin', 'user'],
};

const result = generate(jsonData, { rootName: 'User' });
console.log(result.code);

输出结果:

/**
 * Generated by type-flash
 * Root type: User
 */

export interface User {
  email: string;
  id: number;
  name: string;
  profile: UserProfile;
  tags: string[];
}

export interface UserProfile {
  avatar: string;
  bio: string;
}

📖 使用方式

1. 编程式 API

基础用法

import { generate, generateFromString } from 'type-flash';

// 从 JS 对象生成
const result1 = generate({ name: 'foo', age: 25 }, { rootName: 'User' });

// 从 JSON 字符串生成
const result2 = generateFromString('{"name": "foo"}', { rootName: 'User' });

// 获取生成的代码
console.log(result1.code);

// 获取所有类型定义
console.log(result1.types);

分页接口示例

import { generate } from 'type-flash';

const apiResponse = {
  code: 0,
  message: 'success',
  data: {
    list: [
      { id: 1, name: 'Alice', status: 'active' },
      { id: 2, name: 'Bob', status: 'inactive' },
    ],
    total: 100,
    page: 1,
    pageSize: 10,
  },
};

const result = generate(apiResponse, {
  rootName: 'ApiResponse',
  extractGenerics: true,
});

console.log(result.code);

输出:

export interface ApiResponse {
  code: number;
  data: ApiResponseData;
  message: string;
}

export interface ApiResponseData {
  list: PageResult<ListItem>;
  page: number;
  pageSize: number;
  total: number;
}

export interface ListItem {
  id: number;
  name: string;
}

2. CLI 命令行

基础用法

# 从文件生成,输出到控制台
type-flash user.json

# 指定输出文件
type-flash user.json -o user.types.ts

# 自定义根类型名
type-flash user.json -n User

# 使用 type 风格输出
type-flash data.json --style type

高级用法

# 从标准输入读取(管道)
curl https://api.example.com/users | type-flash -n UserList

# 生成带注释的类型定义
type-flash api.json --comments -o api-types.ts

# 严格空值模式
type-flash data.json --strict-null

# 添加类型前缀
type-flash response.json --prefix I -o interfaces.ts

# 不生成 export
type-flash types.json --no-export

所有 CLI 选项

选项 说明 默认值
-i, --input <file> 输入 JSON 文件路径 -
-o, --output <file> 输出 TS 文件路径 stdout
-n, --name <name> 根类型名称 Root
-s, --style <style> 输出风格: interface | type interface
--naming-style <s> 命名风格: PascalCase | camelCase PascalCase
--sort <order> 属性排序: alpha | definition alpha
--no-export 不添加 export 关键字 -
--comments 生成 JSDoc 注释 -
--strict-null 严格空值模式 -
--no-optional 不标记可选属性 -
--no-generics 不提取泛型类型 -
--indent <n> 缩进空格数 2
--prefix <prefix> 类型名前缀 -
--suffix <suffix> 类型名后缀 -
-h, --help 显示帮助 -
-v, --version 显示版本号 -

⚙️ 配置选项

GenerateOptions 完整配置

interface GenerateOptions {
  /** 根类型名称,默认 'Root' */
  rootName?: string;
  
  /** 输出风格:interface 或 type,默认 'interface' */
  outputStyle?: 'interface' | 'type';
  
  /** 命名风格:PascalCase 或 camelCase,默认 'PascalCase' */
  namingStyle?: 'PascalCase' | 'camelCase';
  
  /** 属性排序方式,默认 'alpha' */
  sortProperties?: 'alpha' | 'definition';
  
  /** 是否添加 export 语句,默认 true */
  addExport?: boolean;
  
  /** 是否生成 JSDoc 注释,默认 false */
  addComments?: boolean;
  
  /** 是否严格空值,默认 false */
  strictNullChecks?: boolean;
  
  /** 是否标记可选属性,默认 true */
  markOptional?: boolean;
  
  /** 是否提取泛型,默认 true */
  extractGenerics?: boolean;
  
  /** 缩进空格数,默认 2 */
  indentSize?: number;
  
  /** 自定义类型名映射 */
  typeNameMap?: Record<string, string>;
  
  /** 类型名前缀 */
  typePrefix?: string;
  
  /** 类型名后缀 */
  typeSuffix?: string;
}

配置示例

企业级 DTO 配置

import { generate } from 'type-flash';

const result = generate(jsonData, {
  rootName: 'UserDTO',
  outputStyle: 'interface',
  namingStyle: 'PascalCase',
  typePrefix: 'I',
  typeSuffix: 'DTO',
  addExport: true,
  addComments: true,
  sortProperties: 'alpha',
  extractGenerics: true,
  strictNullChecks: true,
  indentSize: 2,
});

自定义类型名映射

const result = generate(jsonData, {
  rootName: 'ApiResponse',
  typeNameMap: {
    'ApiResponse.data': 'ResponseData',
    'ResponseData.list': 'UserItem',
  },
});

🆚 对比优势

与其他方案对比

特性 type-flash json-schema-to-typescript 在线转换工具 quicktype
直接输入 JSON ❌ 需要 JSON Schema
嵌套对象自动命名 ✅ 智能命名 ⚠️ 简单命名
联合类型推断 ⚠️ 有限支持
可选属性识别
枚举自动提取 ⚠️ 需手动定义
泛型模式识别
结构等价去重 ⚠️ 有限
循环引用处理
JSDoc 注释生成
CLI 命令行
编程式 API
零依赖 ❌ 依赖多 - ❌ 包体大
体积大小 ~10KB ~100KB - ~500KB

如果觉得好用,别忘了给个 ⭐ Star 支持一下!