@flink-app/ts-source-to-json-schema

中文文档
0.1.9发布于 2026/08/19MITTypeScriptESM + CJS零依赖近 30 天下载 4206

零依赖性 TypeScript- to-JSON Schema 转换器,该转换器使用自有的小型parser

中文使用文档
文档目录26 节
  1. 为什么
  2. 它处理什么
  3. 安装
  4. CLI 使用量
  5. CLI 选项
  6. 多功能支持( O) --followImports (中文(简体) )
  7. 批量模式( E) --batch (中文(简体) )
  8. 诊断模式 --doctor (中文(简体) )
  9. 程序用途
  10. 基于字符串的 API
  11. 基于文件的 API 有导入分辨率
  12. 批量外观生成
  13. 选项
  14. includeJSDoc (可选)
  15. includeSchema (可选)
  16. schemaVersion (可选)
  17. additionalProperties (可选)
  18. @additionalProperties JSDoc 标签
  19. 阵列属性上的 JSDoc 标记
  20. @oneOf 编号 : @anyOf JSDoc 标记
  21. followImports (可选)
  22. baseDir (可选)
  23. onDuplicateDeclarations (可选)
  24. onUnresolvedReferences (可选)
  25. defineId (可选)
  26. 处理不了的

ts- to-jsonschema (日语)

一个零依赖性 TypeScript-to-JSON Schema 转换器,它使用自己的微型parser来代替 TypeScript 编译器.

它从源字符串直接解析出TypeScript类型声明(介面,类型别名,enums)并发出JSON Schema(2020-12草稿). 没有 ts.createProgram,没有 node_modules bloat, 无编译器启动成本 .

为什么

现有工具,如 ts-json-schema-generator 财务报告和审定财务报表 typescript-json-schema 依赖完整的 TypeScript 编译器 API 来解决类型。 这很有效,但很慢很重,而且你和Node.js有联系. 此外,当TypeScript 7(tsgo)发布时,这些图书馆可能需要大量重写,使其长期的未来不确定.

这个库采取不同的方法:它不是运行类型检查器,而是将类型检查符作为符号并描述a 实用子集 直接使用 TypeScript 类型语法。 结果是一个足够快能跑入热道的工具,可移植到任何地方可以跑(Cloudflare Workers,浏览器,CLI),并且简单能扩展.

权衡是明确的:它处理你实际在API合同中使用的类型构造,工具计划,以及配置定义——而不是完整的类型级编程语言.

它处理什么

  • 声明数字 : interface, (中文(简体) ), type, (中文(简体) ), enum (字符串+数字), export
  • 初级数字 : string, (中文(简体) ), number, (中文(简体) ), boolean, (中文(简体) ), null, (中文(简体) ), undefined, (中文(简体) ), any, (中文(简体) ), unknown, (中文(简体) ), never, (中文(简体) ), void, (中文(简体) ), bigint
  • 内建类型数字 : Date → { type: "string", format: "date-time" }
  • 文字类型数字 : "active", (中文(简体) ), 42, (中文(简体) ), true
  • 工会数字 : A | B | C → anyOf (或 enum 当全体会员都是字迹的时候
  • 交叉数字 : A & B → allOf
  • 阵列数字 : T[], (中文(简体) ), Array<T>,筑起 T[][]
  • Tu数字 : [string, number] → prefixItems
  • 无效数字 : string | null → type: ["string", "null"]
  • 嵌入对象: 内置 { foo: string } 和通过 $ref
  • 自我优惠类型数字 : Task 包含 subtasks: Task[]
  • 接口扩展数字 : interface Dog extends Animal → allOf
  • 索引签名数字 : [key: string]: T → additionalProperties
  • 通用类型即时处理数字 : interface Foo extends Generic<TypeArg> + 有类型参数替代的内线
    • 支持带有类型参数的接口和类型化名
    • 掌巢通论: Box<Box<string>>
    • 带有任意名称的多类型参数 : Pair<T, U>, (中文(简体) ), ApiResponse<TData>, (中文(简体) ), Pair<First, Second>
    • 限制和默认被接受(<T extends string = "a">),虽然没有执行
    • 类型参数在整个属性,阵列,结合等中被替换.
    • 倒计时 $ref 当找不到通用定义时
  • 职能/方法成员数字 : onChange: (value: string) => void 财务报告和审定财务报表 findById(id: string): User 在计划(职能没有JSON代表)中省略,而不是转换失败
  • 工具类型数字 : Partial<T>, (中文(简体) ), Required<T>, (中文(简体) ), Pick<T, K>, (中文(简体) ), Omit<T, K>, (中文(简体) ), Record<K, V>, (中文(简体) ), Readonly<T>, (中文(简体) ), Set<T>, (中文(简体) ), Map<K, V>, (中文(简体) ), Promise<T> (未包装)
  • 当地进口: 自动解决相对进口(./ 财务报告和审定财务报表 ../横跨文件
  • 联合来文文件数字 : /** description */ → description,加标签: @minimum, (中文(简体) ), @maximum, (中文(简体) ), @minLength, (中文(简体) ), @maxLength, (中文(简体) ), @pattern, (中文(简体) ), @format, (中文(简体) ), @minItems, (中文(简体) ), @maxItems, (中文(简体) ), @uniqueItems, (中文(简体) ), @default, (中文(简体) ), @deprecated, (中文(简体) ), @title, (中文(简体) ), @example, (中文(简体) ), @additionalProperties, (中文(简体) ), @oneOf, (中文(简体) ), @anyOf
    • 数组属性( O)string[], (中文(简体) ), Array<T>,.) 价值约束如 @format uuid 适用于 项目这样 /** @format uuid */ to: string[] 验证每个元素
    • @oneOf 编号 : @anyOf 表示跨战区规则 : @oneOf required(message, to) | required(message, conversationId); 一个裸体 @oneOf 在工会类型中的别名 oneOf 改为 anyOf
  • 只读数字 : readonly → readOnly 计划

安装

npm install ts-source-to-json-schema

CLI 使用量

软件包包括一个将 TypeScript 文件转换为 JSON Schema 的命令行工具:

# Convert a TypeScript file
npx ts-source-to-json-schema src/types.ts

# Convert with automatic import resolution (default)
npx ts-source-to-json-schema src/api.ts

# Convert a specific type as the root schema
npx ts-source-to-json-schema src/api.ts --rootType ApiResponse

# Use strict mode (no additional properties allowed)
npx ts-source-to-json-schema src/config.ts --strictObjects

# Disable JSDoc processing
npx ts-source-to-json-schema src/types.ts --includeJSDoc false

# Single file mode, no imports
npx ts-source-to-json-schema src/types.ts --followImports none

# Combine multiple options
npx ts-source-to-json-schema src/user.ts -r User --strictObjects --followImports local

CLI 选项

-h, --help                     Show help message
-v, --version                  Show version number
    --doctor                   Output diagnostic information for debugging
    --batch                    Batch mode: generate schemas for all types across files

-r, --rootType <name>          Emit this type as root (others in $defs)
-s, --includeSchema <bool>     Include $schema property (default: true)
    --schemaVersion <url>      Custom $schema URL
    --strictObjects            Set additionalProperties: false globally
    --additionalProperties     Set additionalProperties default (true/false)
    --includeJSDoc <bool>      Include JSDoc comments (default: true)

--followImports <mode>         Follow imports: none, local, all (default: local)
--baseDir <path>               Base directory for resolving imports

CLI 读取 TypeScript 文件并输出 JSON Schema 到 stdout, 使其易于向文件或其他工具管道 :

# Save to file
npx ts-source-to-json-schema src/types.ts > schema.json

# Pretty-print with jq
npx ts-source-to-json-schema src/types.ts | jq '.'

# Use in scripts
npx ts-source-to-json-schema src/api.ts --rootType Request > openapi/request-schema.json

多功能支持( O)--followImports(中文(简体) )

默认情况下, CLI 自动跟随本地相对进口(./ 财务报告和审定财务报表 ../解决多个文件中的类型定义:

// pet.ts
export interface Pet {
  _id: string;
  name: string;
  species: string;
}

// api.ts
import { Pet } from './pet';
export interface PostPetReq extends Omit<Pet, "_id"> {}
# Follows imports and resolves Pet type (default behavior)
npx ts-source-to-json-schema api.ts --rootType PostPetReq

# Output includes both Pet (in $defs) and PostPetReq (as root)

导入分辨率模式 :

  • local (在 CLI 中默认): 随相对进口(./ 财务报告和审定财务报表 ../),跳过 node_modules
  • none: 单文件模式, 不遵循任何导入
  • all: 预留的未来 node_modules 支持( 目前行为如下 ) local(中文(简体) )

关键特性 :

  • 循环依赖检测( 无无限循环)
  • 复制名称检测( 如果多个文件中的同类型名称有错误)
  • 自动扩展分辨率( E).ts, (中文(简体) ), .tsx, (中文(简体) ), .d.ts(中文(简体) )
  • 索引文件支持( E)./types → ./types/index.ts(中文(简体) )

实例:

# Multi-file project with local imports
npx ts-source-to-json-schema src/api.ts --followImports local

# Single file only, ignore imports
npx ts-source-to-json-schema src/standalone.ts --followImports none

# Custom base directory for import resolution
npx ts-source-to-json-schema src/api.ts --baseDir ./src

批量模式( E)--batch(中文(简体) )

使用 --batch 以同时生成跨多个文件的所有类型的计划。 接受 glob 模式或多个文件路径 :

# Batch: all schemas from matching files
npx ts-source-to-json-schema --batch 'src/schemas/**/*.ts' --followImports local

# Batch: specific files
npx ts-source-to-json-schema --batch src/PostReq.ts src/PostRes.ts --followImports local

# Batch with strict objects
npx ts-source-to-json-schema --batch 'src/types/*.ts' --strictObjects

输出是一个 JSON 对象, 其中密钥是类型名称, 值是独立的计划 :

{
  "PostReq": { "$schema": "...", "type": "object", "properties": { ... } },
  "PostRes": { "$schema": "...", "type": "object", "properties": { ... } }
}

共享进口一经解决,并在所有条目文件中被复制.

诊断模式--doctor(中文(简体) )

当遇到计划转换时,请使用 --doctor 以显示可与开发者共享的全面诊断信息:

npx ts-source-to-json-schema src/problematic-types.ts --doctor

医生产出包括:

  • 时间戳: 当转换尝试时
  • 环境: Node.js 版本,平台,架构,以及当前工作目录
  • 输入文件细节: 路径、存在、大小、修改时间、源长度和完整源代码
  • 使用的选项: 所有配置选项都传递给转换器
  • 转换结果: 成功生成的图案或带有堆栈痕迹的详细错误信息

这使得:

  1. 报告问题时复制全部诊断结果
  2. 调试特定类型Script文件为何没有按预期转换
  3. 与维护者共享可复制的实例

示例输出 :

{
  "timestamp": "2026-02-25T10:50:55.680Z",
  "environment": {
    "nodeVersion": "v20.17.0",
    "platform": "darwin",
    "arch": "arm64",
    "cwd": "/path/to/project"
  },
  "input": {
    "filePath": "types.ts",
    "absolutePath": "/absolute/path/to/types.ts",
    "fileExists": true,
    "fileSize": 486,
    "sourceLength": 486,
    "source": "interface User { ... }"
  },
  "options": { "rootType": "User" },
  "conversionResult": {
    "success": true,
    "schema": { ... }
  }
}

程序用途

基于字符串的 API

import { toJsonSchema } from "ts-source-to-json-schema";

const schema = toJsonSchema(`
  /** Input for the ad analysis tool */
  interface AnalyzeAdInput {
    /** URL of the ad to analyze */
    url: string;
    /** Platform the ad is from */
    platform: "instagram" | "facebook" | "tiktok";
    /** Whether to extract color palette */
    extractColors?: boolean;
    /** Max elements to identify
     * @minimum 1
     * @maximum 50
     * @default 10
     */
    maxElements?: number;
    tags: string[];
  }
`, { rootType: "AnalyzeAdInput" });

基于文件的 API 有导入分辨率

import { toJsonSchemaFromFile } from "ts-source-to-json-schema";

// Convert a TypeScript file with automatic import resolution
const schema = toJsonSchemaFromFile('./src/types/api.ts', {
  followImports: 'local',  // Follow relative imports
  rootType: 'ApiRequest',
  strictObjects: true
});

// Single-file mode (no import resolution)
const singleFileSchema = toJsonSchemaFromFile('./src/types.ts', {
  followImports: 'none'
});

批量外观生成

当需要同一源文件中的多个类型时,请使用 toJsonSchemas() 为了更好的表现 这对于构建工具,文档生成器,或同时处理多类型的API schema验证器特别有用.

import { toJsonSchemas } from "ts-source-to-json-schema";

const source = `
  export interface User { id: string; name: string; }
  export interface Post { id: string; title: string; author: User; }
  export interface Comment { id: string; text: string; }
`;

// Generate all schemas at once (~70% faster than calling toJsonSchema() for each type)
const schemas = toJsonSchemas(source);

console.log(schemas.User);    // Standalone User schema
console.log(schemas.Post);    // Post schema with User in definitions
console.log(schemas.Comment); // Standalone Comment schema

主要好处:

  • 业绩: 当生成来自同一来源的30+个计划时速度快于~70%
  • 单页: 源代码化,仅解析一次
  • 独立的计划:每个方案只包括在其中提及的类型 definitions 字段
  • 自成一体: 每个方案包括: $schema 默认字段,用于更好的 IDE 验证
  • 兼容的07号草案: 用途 definitions 改为 $defs 用于更广泛的兼容性

如何运作:

  • 一次解析源并发布所有类型声明
  • 每个计划都是独立的 最少 definitions (仅中转引用类型)
  • 用途 #/definitions/TypeName 参考书目代替 #/$defs/TypeName
  • 处理循环参考、过渡依赖和公用事业类型

使用大小写 :

  • 框架集成(如Flink),需要来自一个来源的许多计划
  • 为所有 API 定义文件构建生成计划的工具
  • 处理大类型文件的文件生成器
  • Schema 验证库缓存多个方案

以真实世界 API 为例:

const schemas = toJsonSchemas(`
  interface User { id: string; name: string; }
  interface CreateUserRequest { name: string; }
  interface CreateUserResponse { user: User; }
  interface GetUserRequest { id: string; }
  interface GetUserResponse { user: User; }
`, { includeJSDoc: true, strictObjects: true });

// Extract specific schemas as needed
const requestSchemas = {
  CreateUser: schemas.CreateUserRequest,
  GetUser: schemas.GetUserRequest
};

带有导入分辨率的批量生成

如果您的类型分布在多个文件的导入处,则使用 toJsonSchemasFromFile() (基于文件的批次 API):

import { toJsonSchemasFromFile } from "ts-source-to-json-schema";

// Intermediate schema file (e.g., generated by a framework)
// schemas.ts:
//   import TreeNode from "../../src/schemas/TreeNode";
//   import Car from "../../src/schemas/Car";
//   export interface GetTree_12_ResSchema extends TreeNode {}
//   export interface GetCar_10_ResSchema extends Car {}

const schemas = toJsonSchemasFromFile('./schemas.ts', {
  followImports: 'local',  // Resolve relative imports
  strictObjects: true
});

console.log(schemas.GetTree_12_ResSchema);
// {
//   "$ref": "#/definitions/TreeNode",
//   "definitions": {
//     "TreeNode": { "type": "object", ... }  // ✅ Included from imported file!
//   }
// }

为什么用 toJsonSchemasFromFile()? 吗?

  • 从本地文件自动解析导入
  • 生成所有类型( 如 toJsonSchemas()(中文(简体) )
  • 处理文件之间的循环依赖
  • 适合框架集成( 如 Flink) 和生成的中间文件

性能 : 批次性能效益与 toJsonSchemas(),加上自动导入分辨率.

多条目批次生成

当需要从多个 TypeScript 文件生成计划(不仅仅是一个条目文件)时,使用 toJsonSchemasFromFiles()。它接受 glob 模式或一系列文件路径 :

import { toJsonSchemasFromFiles } from "ts-source-to-json-schema";

// Glob pattern — matches all .ts files in src/schemas/
const schemas = toJsonSchemasFromFiles('src/schemas/**/*.ts', {
  followImports: 'local'
});

// Array of specific files
const schemas = toJsonSchemasFromFiles([
  'src/schemas/PostUserReq.ts',
  'src/schemas/PostUserRes.ts'
], { followImports: 'local' });

// With defineNameTransform for namespacing
const schemas = toJsonSchemasFromFiles('src/schemas/**/*.ts', {
  followImports: 'local',
  defineNameTransform: (name, decl, ctx) => {
    const file = path.basename(ctx?.relativePath ?? '', '.ts');
    return `${file}.${name}`;
  }
});

主要利益超过 toJsonSchemasFromFile()数字 :

  • 接受多个条目文件或 glob 模式( 不仅仅是一个文件)
  • 共享的导入处理一次, 并在所有条目文件中复制
  • 与 defineNameTransform,允许在所有计划中使用稳定的类型标识
  • 回返 {} 当文件没有匹配时( 空格的安全性)

Glob 支持 :

  • * 匹配文件/目录名称中的任何字符
  • ** 匹配零或更多目录级别
  • ? 匹配单个字符

输出 :

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "description": "Input for the ad analysis tool",
  "properties": {
    "url": { "type": "string", "description": "URL of the ad to analyze" },
    "platform": {
      "type": "string",
      "enum": ["instagram", "facebook", "tiktok"],
      "description": "Platform the ad is from"
    },
    "extractColors": { "type": "boolean", "description": "Whether to extract color palette" },
    "maxElements": {
      "type": "number",
      "description": "Max elements to identify",
      "minimum": 1,
      "maximum": 50,
      "default": 10
    },
    "tags": { "type": "array", "items": { "type": "string" } }
  },
  "required": ["url", "platform", "tags"]
}

选项

toJsonSchema(source, {
  rootType: "MyType",            // Emit this type as the root schema (others go in $defs)
  includeSchema: true,           // Include $schema field (default: true)
  strictObjects: false,          // Set additionalProperties: false on all objects
  schemaVersion: "https://json-schema.org/draft/2020-12/schema",
  includeJSDoc: true,            // Include JSDoc descriptions and tags (default: true)
  additionalProperties: undefined, // Default value for additionalProperties (undefined, true, or false)
  onUnresolvedReferences: 'ignore', // Handle dangling $refs: 'error', 'warn', 'ignore' (default)
});

toJsonSchemaFromFile(filePath, {
  // All options from toJsonSchema, plus:
  followImports: 'local',        // Follow imports: 'none' (default for API), 'local' (default for CLI), 'all'
  baseDir: './src',              // Base directory for resolving imports (default: dirname(filePath))
  onDuplicateDeclarations: 'error', // Handle duplicate type names: 'error' (default), 'warn', 'silent'
});

toJsonSchemasFromFile(filePath, {
  // All options from toJsonSchemas, plus:
  followImports: 'local',        // Follow imports: 'none', 'local' (default), 'all'
  baseDir: './src',              // Base directory for resolving imports (default: dirname(filePath))
  onDuplicateDeclarations: 'error', // Handle duplicate type names: 'error' (default), 'warn', 'silent'
  // Note: rootType is not supported (generates schemas for all types)
});

toJsonSchemasFromFiles(entries, {
  // entries: glob pattern (string) or array of file paths
  // All options from toJsonSchemas, plus:
  followImports: 'local',        // Follow imports: 'none' (default), 'local', 'all'
  baseDir: './src',              // Base directory for resolving imports (default: cwd)
  onDuplicateDeclarations: 'error', // Handle duplicate type names: 'error' (default), 'warn', 'silent'
  // Note: rootType is not supported (generates schemas for all types)
});

includeJSDoc (可选)

  • 类型 : boolean
  • 默认 : true
  • 说明 : 控制JSDoc评论是否得到处理并纳入计划

何时 true (默认) :

  • 界面/类型描述取自JSDoc的评论
  • 包括财产说明
  • JSDoc 标签类 @minimum, (中文(简体) ), @maximum, (中文(简体) ), @pattern 作为限制适用

何时 false数字 :

  • JSDoc的所有评论均被忽略
  • Schema只包含结构信息(类型、属性、需要的字段)
  • 用于生成最低限度的图案或当不需要描述时

示例

const schema = toJsonSchema(`
  /** User profile */
  interface User {
    /** @minLength 1 */
    name: string;
  }
`, { rootType: 'User', includeJSDoc: false });

// Result: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }
// No description or minLength constraint

includeSchema (可选)

  • 类型 : boolean
  • 默认 : true
  • 说明 : 是否控制 $schema 字段包含在生成的计划中

何时 true (默认) :

  • 每个生成的图案包括: $schema 字段指向 JSON Schema 规格
  • 使计划自成一体并改进IDE验证支持
  • 使用来自 schemaVersion 选项( 默认 ): https://json-schema.org/draft/2020-12/schema(中文(简体) )

何时 false数字 :

  • 这个 $schema 字段在所有生成的计划中被省略
  • 在更大的文档中嵌入计划或者在其他地方管理计划版本时有用

示例

const schema = toJsonSchema(`
  interface User {
    name: string;
  }
`, { rootType: 'User', includeSchema: true });

// Result includes: { "$schema": "https://json-schema.org/draft/2020-12/schema", type: 'object', ... }

批量生成 : 这个 toJsonSchemas() 函数也尊重此选项并包含 $schema 在默认情况下,每个方案都生成.

schemaVersion (可选)

  • 类型 : string
  • 默认 : "https://json-schema.org/draft/2020-12/schema"
  • 说明 : 指定 JSON Schema 草稿版本 URL

使用它来生成与不同的 JSON Schema 草稿兼容的策略 :

// Generate draft-07 compatible schema
const schema = toJsonSchema(`interface User { name: string; }`, {
  rootType: 'User',
  schemaVersion: 'http://json-schema.org/draft-07/schema#'
});

// Result includes: { "$schema": "http://json-schema.org/draft-07/schema#", ... }

说明: 这个库总是生成草稿-2020-12相容的计划. 这个 schemaVersion 选项仅更改 $schema 字段值。 对于与草稿07的最大兼容性,使用 toJsonSchemas() 用于 definitions 改为 $defs。 。 。 .

additionalProperties (可选)

  • 类型 : boolean | undefined
  • 默认 : undefined
  • 说明 : 设置默认值 additionalProperties 在所有对象计划上

此选项提供了全局默认值 additionalProperties 如果未通过 JSDoc 或索引签名明确设定.

优先级( 从最高到最低):

  1. 索引签名 : [key: string]: T → additionalProperties: T
  2. 联合来文文件 @additionalProperties 标签
  3. strictObjects 选项
  4. additionalProperties 选项
  5. 未设置( JSON Schema 默认行为)

示例

// Set all objects to disallow additional properties by default
const schema = toJsonSchema(`
  interface User {
    name: string;
  }
`, { rootType: 'User', additionalProperties: false });

// Result: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false }

@additionalProperties JSDoc 标签

控制权 additionalProperties 特定类型或属性,使用 @additionalProperties JSDoc标签.

支持的数值 : true | false (对大小写不敏感)

界面/类型级的使用 :

/**
 * Strict configuration object
 * @additionalProperties false
 */
interface Config {
  host: string;
  port: number;
}
// Result: { type: 'object', properties: {...}, additionalProperties: false }

财产一级的使用:

interface Settings {
  /**
   * Database configuration
   * @additionalProperties false
   */
  database: {
    host: string;
    port: number;
  };
}
// Result: database property has additionalProperties: false

与其他选项的相互作用:

  • 何时 includeJSDoc: false标记被忽略
  • 标签覆盖全局 additionalProperties 财务报告和审定财务报表 strictObjects 选项
  • 索引签名优先于标签

阵列属性上的 JSDoc 标记

在数组类型的属性上(T[], (中文(简体) ), Array<T>, (中文(简体) ), readonly T[], (中文(简体) ), Set<T>, (中文(简体) ), T[] | null,筑起 T[][]),数值 限制说明 要素,因此适用于 items 而不是数组本身 JSON Schema默默地忽略他们:

interface SendMessageRequest {
  /**
   * @format uuid
   * @minItems 1
   * @uniqueItems
   */
  to: string[];
}
// Result:
// to: { type: 'array', items: { type: 'string', format: 'uuid' }, minItems: 1, uniqueItems: true }
适用于 items留在阵列上
@format, (中文(简体) ), @pattern, (中文(简体) ), @minLength, (中文(简体) ), @maxLength, (中文(简体) ), @minimum, (中文(简体) ), @maximum, (中文(简体) ), @additionalProperties@minItems, (中文(简体) ), @maxItems, (中文(简体) ), @uniqueItems, (中文(简体) ), @title, (中文(简体) ), @default, (中文(简体) ), @example, (中文(简体) ), @deprecated,说明

Tu( 二[string, number]这些因素各不相同.

@oneOf 编号 : @anyOf JSDoc 标记

TypeScript 接口不能表示“这些字段或那些字段”。 这个 @oneOf 财务报告和审定财务报表 @anyOf 标记允许声明(或内置对象属性)声明跨字段要求为 |- 分开的一组财产名称。 每个组都变成 { required: [...] } 组合符下:

/**
 * Either (message + to) or (message + conversationId), never both.
 * @oneOf required(message, to) | required(message, conversationId)
 */
interface SendMessageRequest {
  message: string;
  to?: string[];
  conversationId?: string;
}
// Result:
// {
//   type: 'object',
//   properties: { ... },
//   required: ['message'],
//   oneOf: [ { required: ['message', 'to'] }, { required: ['message', 'conversationId'] } ]
// }

/** @anyOf required(email) | required(phoneNumber) | required(skypeId) */
interface ContactRequest {
  email?: string;
  phoneNumber?: string;
  skypeId?: string;
}
// Result: anyOf: [ { required: ['email'] }, { required: ['phoneNumber'] }, { required: ['skypeId'] } ]

这个 required(...) 包装是可选的—— @anyOf email | phoneNumber | skypeId 等同的.

工会: 对象类型的结合作为 anyOf (匹配类型Script语义,其中的值) (可满足若干成员的要求)。 添加一个赤色 @oneOf 当一个成员必须完全匹配时,该类型改为:

/** @oneOf */
export type SendMessageRequest =
  | { message: string; to: string[]; referenceId?: string }
  | { message: string; conversationId: string };
// Result: { oneOf: [ { type: 'object', ... }, { type: 'object', ... } ] }

两种标记在 includeJSDoc: false。 。 。 .

followImports (可选)

  • 类型 : "none" | "local" | "all"
  • 默认 : "none" (方案API), "local" (CLI) (英语)
  • 说明 : 跨越多个类型Script文件的导入分辨率控制

模式 :

  • none: 单文件模式, 导入被忽略
  • local: 遵循相对进口(./ 财务报告和审定财务报表 ../),跳过 node_modules
  • all: 预留的未来 node_modules 支持( 目前行为如下 ) local(中文(简体) )

仅可用基于文件的 API (单位:千美元)toJsonSchemaFromFile(), (中文(简体) ), toJsonSchemasFromFile(),以及 toJsonSchemasFromFiles())——以字符串为基础的API(toJsonSchema() 财务报告和审定财务报表 toJsonSchemas())不支持导入分辨率.

示例

// Given: pet.ts exports Pet interface
// Given: api.ts imports Pet and uses it in PostPetReq

const schema = toJsonSchemaFromFile('./api.ts', {
  followImports: 'local',
  rootType: 'PostPetReq'
});

// Result: Schema includes both Pet (in $defs) and PostPetReq

特征 :

  • 循环依赖检测(预防无限循环)
  • 复制名称处理( 可配置于 onDuplicateDeclarations 选项)
  • 自动扩展分辨率( E).ts, (中文(简体) ), .tsx, (中文(简体) ), .d.ts(中文(简体) )
  • 索引文件分辨率 (E)./types → ./types/index.ts(中文(简体) )

baseDir (可选)

  • 类型 : string
  • 默认 : path.dirname(filePath)
  • 说明 : 解析相对导入的基础目录

只有当 followImports 没有 "none"。 。 。 .

onDuplicateDeclarations (可选)

  • 类型 : "error" | "warn" | "silent"
  • 默认 : "error"
  • 说明 : 控制如何处理多个文件的重复类型名称

只有当 followImports 没有 "none" (需要导入分辨率).

模式 :

  • error (默认):在多个文件中找到相同类型名称时丢出错误
  • warn: 使用遇到的第一个声明,并将警告记录到 console.warn
  • silent: 在没有任何警告的情况下使用第一次声明

何时使用 :

  • error: 捕捉无意重复的严格模式(多数情况下建议)
  • warn: 需要通知但不能阻断执行的开发模式
  • silent: 当您有意重复并想要使用第一次声明时

示例

// File 1: schemas/CampaignImage.ts
export interface ImageDimensions {
  width: number;
  height: number;
  format?: string;
}

// File 2: schemas/BrandAsset.ts
export interface ImageDimensions {
  width: number;
  height: number;
  format: string;  // Required (different from File 1)
}

// With error mode (default) - throws error
toJsonSchemaFromFile('entry.ts', {
  followImports: 'local'
});
// Error: Duplicate declaration "ImageDimensions" found in:
//   .../CampaignImage.ts
//   .../BrandAsset.ts

// With warn mode - uses first declaration
toJsonSchemaFromFile('entry.ts', {
  followImports: 'local',
  onDuplicateDeclarations: 'warn'
});
// Warning: Duplicate declaration "ImageDimensions" found...
// Uses ImageDimensions from CampaignImage.ts (format is optional)

// With silent mode - uses first declaration without warning
toJsonSchemaFromFile('entry.ts', {
  followImports: 'local',
  onDuplicateDeclarations: 'silent'
});
// No warning, uses ImageDimensions from CampaignImage.ts

最佳做法: 保留默认 error 模式以提早抓取重复名称。 如果遇到重复:

  1. 检查类型在结构上是否相同- 如果相同, 提取到共享文件
  2. 如果它们不同,但名字相同, 改名其中之一清晰
  3. 使用 warn 或者说 silent 模式仅作为临时工作

onUnresolvedReferences (可选)

  • 类型 : "error" | "warn" | "ignore"
  • 默认 : "ignore"
  • 说明 : 控制处理方式 $ref 指向未在发射计划中定义的类型

提及来源中未声明的类型(类型,或由于 followImports 实值 "none"制作一个图案, 并缠绕 $ref ——它看起来是有效的,但后来当像AJV这样的验证器试图解决它时失败了.

模式 :

  • error: 扔出一个错误, 列出未解决的类型名称( 以批量模式, 其中包含这些名称)
  • warn: 将计程器输入并记录一个警告 console.warn
  • ignore (默认) : 以- 身份表示计划, 保留先前的行为

示例

// "Customer" is referenced but never declared
toJsonSchema(`interface Order { customer: Customer }`, {
  rootType: 'Order',
  onUnresolvedReferences: 'error'
});
// Error: Unresolved type reference: Customer. The referenced type(s) are
// not defined in the provided source. Define them, enable followImports,
// or set onUnresolvedReferences to "warn" or "ignore".

最佳做法: 设定 'error' 或建造管道,在生成时而不是在验证时捕捉伤寒和缺失的进口。 默认保留 'ignore' 对于后向相容性——有意携带外部引用(由您的验证器的注册所解决)的策略继续工作.

与 toJsonSchema, (中文(简体) ), toJsonSchemas,以及基于文件的变体.

defineId (可选)

  • 类型 : (originalName: string, declaration: Declaration, context?: { absolutePath: string; relativePath: string }) => string
  • 默认 : undefined
  • 说明 : 指定 a $id 并使用外部 $ref 代替本地 #/definitions/ 参考

当设定在批量 API (toJsonSchemas, (中文(简体) ), toJsonSchemasFromFile, (中文(简体) ), toJsonSchemasFromFiles:

  1. 每一个计划都有一个 $id 字段( 回调值)
  2. 内部 $ref 指针变成外向指针 $id 类型
  3. 这个 definitions 块被完全省略
  4. 这个 $id 在返回时用作密钥 Record<string, JSONSchema>

设计用于: AJV的全球登记册,则由 $id 和交叉引用在验证时解决.

AJV 示例:

import { toJsonSchemas } from "ts-source-to-json-schema";
import Ajv from "ajv";

const schemas = toJsonSchemas(`
  interface User { id: string; name: string; }
  interface Post { title: string; author: User; }
`, {
  defineId: (name) => \`schemas.\${name}\`
});

// schemas = {
//   "schemas.User": {
//     "$id": "schemas.User",
//     "$schema": "...",
//     "type": "object",
//     "properties": { "id": { "type": "string" }, "name": { "type": "string" } }
//   },
//   "schemas.Post": {
//     "$id": "schemas.Post",
//     "$schema": "...",
//     "type": "object",
//     "properties": { "title": { "type": "string" }, "author": { "$ref": "schemas.User" } }
//   }
// }

// Register all schemas with AJV
const ajv = new Ajv();
for (const schema of Object.values(schemas)) {
  ajv.addSchema(schema);
}

// Validate — AJV resolves $ref: "schemas.User" from its global registry
const validate = ajv.getSchema("schemas.Post");
validate({ title: "Hello", author: { id: "1", name: "Joel" } }); // ✅

名称间隔的文件上下文 :

const schemas = toJsonSchemasFromFiles('src/schemas/**/*.ts', {
  followImports: 'local',
  defineId: (name, decl, ctx) => {
    const dir = ctx?.relativePath.replace(/\.ts$/, '').replace(/\//g, '.') ?? '';
    return dir ? \`\${dir}.\${name}\` : name;
  }
});

可与 defineNameTransform ——两种选择都是独立的. defineId 控件 $id外部 $ref时 defineNameTransform 控件 $defs编号 :#/definitions/ 名称.

掷出 如果回调时返回重复 $id 不同类型值.

处理不了的

需要类型检查器评估的任何信息 :

  • 有条件的类别T extends U ? X : Y(中文(简体) )
  • 调制类型( E){ [K in keyof T]: ... }(中文(简体) )
  • 模板字面类型( E)`${A}-${B}`(中文(简体) )
  • typeof, (中文(简体) ), keyof, (中文(简体) ), infer
  • node_modules 进口(计划今后进口)

通用类型参数注释 :

  • 类型参数名称从声明中解析出, 因此任何名称工作 : Box<TValue>, (中文(简体) ), Pair<First, Second>
  • 制约因素extends ...)和默认(= ...)被解析,但未得到执行或适用——必须始终明确通过一种类型的论据

函数和方法类型 (单位:千美元)onChange: (v: string) => void, (中文(简体) ), save(): void)在JSON Schema中不能代表. 它们从产出中解析并省去,而不是当作出错处理.

如果你需要这些,请使用 ts-json-schema-generator。如果您的类型看起来像 API 合同和工具定义, 这可能是你所需要的.

版本与发布记录

@flink-app/ts-source-to-json-schema 共发布 10 个版本,首次发布于 2026/02/25;过去 12 个月发布了 10 个版本。

版本发布日期距今
0.1.9latest2026/08/192 个月前
0.1.82026/06/035 个月前
0.1.72026/03/118 个月前
0.1.62026/03/038 个月前
0.1.52026/02/278 个月前
0.1.42026/02/278 个月前

关于 @flink-app/ts-source-to-json-schema 的常见问题

@flink-app/ts-source-to-json-schema 是什么?

零依赖性 TypeScript- to-JSON Schema 转换器,该转换器使用自有的小型parser

如何安装 @flink-app/ts-source-to-json-schema?

在项目目录运行 npm install @flink-app/ts-source-to-json-schema,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 ts-source-to-json-schema,可以用 npx ts-source-to-json-schema 直接运行。

@flink-app/ts-source-to-json-schema 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@flink-app/ts-source-to-json-schema 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@flink-app/ts-source-to-json-schema 可以商用吗?

@flink-app/ts-source-to-json-schema 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@flink-app/ts-source-to-json-schema 的下载量有多少?

根据 npm 官方下载统计,@flink-app/ts-source-to-json-schema 在 2026/10/15 – 2026/11/13 这 30 天内被下载 4,206 次,日均约 140 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@flink-app/ts-source-to-json-schema 还在维护吗?

最新版本 0.1.9 发布于 2026/08/19(2 个月前);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/02/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。