@adbros/typegen

中文文档
3.1.1发布于 2025/03/04MITES Module近 30 天下载 2597

A simple generator of TypeScript types from OpenAPI docs

原始使用文档
文档目录4 节
  1. Installation
  2. Usage
  3. Configuration
  4. Example

Typegen

A simple generator of TypeScript types from OpenAPI docs.

Installation

  • Install the NPM package: npm install --save-dev @adbros/typegen.
  • Create a typegen.config.mjs file and export a valid config object from it. See Configuration (below) for details.

Usage

Each time the OpenAPI doc changes, run npx typegen in the directory containing typegen.config.mjs.

Configuration

The typegen.config.mjs file should be present in the current working directory when running the typegen utility. (Usually, it makes most sense for it to reside in the project's root directory -- next to package.json, tsconfig.json, etc.).

The config object exported from typegen.config.mjs (using ESM default export) should have the following properties:

  • inputDoc (required) -- A string containing the path to the input OpenAPI 3.0.x doc.
  • outputDir (required) -- A string containing the path to the output directory.
  • hooks -- An optional child config object containing convenience funtions to be called before/after the type generation itself. Both functions are optional. Both are called with zero arguments. Both may return a promise; the program's execution will be blocked until the promise's resolution. Both may throw or return an eventually rejected promise, in which case the program will be prematurely terminated with a nonzero exit code.
    • before -- Called before the input doc is loaded. Useful e.g. for fetching the doc from an external source, generating the doc from other data, performing custom validation on the doc (and throwing/rejecting on failure to prevent the type generation itself), etc.
    • after -- Called after the type generation is finished and the files written. Useful e.g. for custom post-processing of the generated files.
  • endpoints -- An optional child config object containing options related to the rendering of endpoints as arbitrary TypeScript constructs. If not given, endpoints.ts is not generated at all. If given, it must contain:
    • renderEach -- A function, called for each endpoint (i.e. each path-method pair), that maps available info about the given endpoint to a string containing arbitrary TypeScript code. If a nullish value is returned from the function instead, the given endpoint is excluded from the output. The function is always called with a single argument -- an object containing the following properties:
      • path (string) -- the path as specified in the input doc;
      • method (string) -- the name of the HTTP method in lower case, e.g. post;
      • pathType (string) -- a string literal type or template literal type describing the path including path parameters, e.g. `/customer/${number}/invoices`;
      • requestType (string) -- the type of the request body, e.g. Invoice;
      • responseType (string) -- the type of the response body for status code 200, e.g. { invoices: Invoice[]; totalCount: number };
      • paramsType (string) -- the type describing an object, where each property corresponds to a single query parameter accepted by the endpoint, e.g. GetInvoicesParams (defined in params.ts as e.g. { limit: number; offset: number });
      • paramsExpected (boolean) -- whether there is at least one query parameter accepted by the endpoint;
      • paramsRequired (boolean) -- whether there is at least one query parameter required by the endpoint;
      • bodyExpected (boolean) -- whether the endpoint expects a request body;
      • bodyReturned (boolean) -- whether the endpoint returns a body within each response with status code 200.
    • renderModule -- A function which maps the concatenated output of renderEach calls to a string containing the final TypeScript module. It takes an object with the sole property content.

Example

The following config defines the generation of a valid subtype of an Axios instance, which only permits calls to existing endpoints using overloaded method signatures. This is useful because:

  • calls to nonexistent endpoints are disallowed;
  • correct request bodies/parameters are enforced;
  • the return type -- corresponding to the matching endpoint's response type -- is automatically inferred for each valid call.
export default {
  inputDoc: 'path/to/openapi.yaml',
  outputDir: 'path/to/output/directory'
  endpoints: {
    renderModule: ({ content }) => `export type Api = { ${content} };`,
    renderEach: ({
      method,
      pathType,
      requestType,
      responseType,
      paramsType,
      paramsExpected,
      paramsRequired,
    }) => {
      switch (method) {
        case 'get':
          return paramsExpected
            ? `${method}(
              path: ${pathType},
              config${paramsRequired ? '' : '?'}:
                { params: ${paramsType} },
            ): Promise<{ data: ${responseType} }>;`
            : `${method}(
              path: ${pathType},
            ): Promise<{ data: ${responseType} }>;`;
        case 'post':
        case 'put':
          return `${method}(
            path: ${pathType},
            body: ${requestType},
          ): Promise<{ data: ${responseType} }>;`;
        default:
          return `${method}(
            path: ${pathType},
          ): Promise<{ data: ${responseType} }>;`;
      }
    },
  },
};

版本与发布记录

@adbros/typegen 共发布 12 个版本,首次发布于 2023/07/13;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.1.1latest2025/03/041.7 年前
3.1.02025/01/151.8 年前
3.0.02024/08/202 年前
2.0.02024/06/242 年前
1.7.02024/06/052 年前
1.6.02024/06/052 年前

关于 @adbros/typegen 的常见问题

@adbros/typegen 是什么?

A simple generator of TypeScript types from OpenAPI docs

如何安装 @adbros/typegen?

在项目目录运行 npm install @adbros/typegen,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 typegen,可以用 npx typegen 直接运行。

@adbros/typegen 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/adbros__typegen 是否存在。

@adbros/typegen 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adbros/typegen 可以商用吗?

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

@adbros/typegen 的下载量有多少?

根据 npm 官方下载统计,@adbros/typegen 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,597 次,日均约 87 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adbros/typegen 还在维护吗?

最新版本 3.1.1 发布于 2025/03/04(1.7 年前);至今共发布 12 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/07/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。