# @coobaha/typed-fastify 中文文档

规范地址：https://npmcn.com/package/%40coobaha/typed-fastify/

版本：4\.1\.0
npm 元数据更新时间：2025-11-04T18:55:05.891Z
中文译文更新时间：2026-11-10T18:01:26.416Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40coobaha/typed-fastify
原文对照：https://npmcn.com/package/%40coobaha/typed-fastify/?lang=original
项目主页：https://github.com/Coobaha/typed-fastify
源码仓库：https://github.com/Coobaha/typed-fastify

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：112 kB，34 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：10 个
- peer 依赖：fastify ^4
- 首次发布：2021-02-18T17:17:37.788Z
- 最新版本发布：2025-11-04T18:55:05.669Z
- 近 30 天下载量：10136（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：36（近 12 个月 0 个）

## 中文简介

用于粘贴的意见类型

## 安装

```sh
npm install @coobaha/typed-fastify
```

也可以使用：`pnpm add @coobaha/typed-fastify`、`yarn add @coobaha/typed-fastify`、`bun add @coobaha/typed-fastify`

## README

# 输入快取

[![Build Status](https://img.shields.io/github/actions/workflow/status/coobaha/typed-fastify/main.yml?branch=main&logo=github&style=for-the-badge)](https://github.com/coobaha/typed-fastify/actions/workflows/main.yml) [![Coverage Status](https://img.shields.io/coveralls/github/Coobaha/typed-fastify.svg?style=for-the-badge)](https://coveralls.io/github/Coobaha/typed-fastify?branch=main) [![NPM Version](https://img.shields.io/npm/v/@coobaha/typed-fastify.svg?style=for-the-badge)](https://www.npmjs.com/package/@coobaha/typed-fastify) [![](https://img.shields.io/npm/dm/@coobaha/typed-fastify.svg?style=for-the-badge)](https://www.npmjs.com/package/@coobaha/typed-fastify)

**[在线文件](https://tfs.cooba.me/)**

此软件包添加了强大的 TypeScript 支持以快速化请求处理器并强制操作 处理器将输入用于验证请求参数和答复的系统。 从这个计划,它有两个 东西:

-   根据类型Script Schema进行静态类型检查
    -   `request.body`
    -   `request.headers`
    -   `request.querystring`
    -   `request.params`
    -   `route.path.params` 并被推断和绘制成 `request.params`,也不可能在 schema params 中做一个类型
    -   `reply` 总是基于状态,开发者将无法使用平原 `reply.send()` 不过 被迫首先明确设定状态,据此推断反应类型
-   从 TS Schema 生成 JSON 计划( 使用 [类型标注-json-schema](https://github.com/YousefED/typescript-json-schema) 带有自定义 全部变换 `@tjs` 注释可用于微调输出)
    -   自从我们使用 `typejescript-json-schema`:所有已知的解放限制都继承:
        -   记录没有正确转换, 使用 `{ [k: string]: string }` 改为或提示 `@tjs`
-   运行时使用生成的 JSON schema 验证(可选但强烈推荐,因为它为运行时带来额外的安全性,并确保关于数据的代码假设正确)

[演示视频](https://user-images.githubusercontent.com/2446638/108409543-08b45f00-722f-11eb-905c-06505b57f5fe.mp4)

## 使用量

```sh
npm i @coobaha/typed-fastify

pnpm i @coobaha/typed-fastify

yarn add @coobaha/typed-fastify

```

我们想要建立服务的例子

```
GET / => Hello ($querystring.name || world)
```

简单执行而不产生计划将遵循

```typescript
import addSchema, { Schema } from '@coobaha/typed-fastify';
import fastify from 'fastify';

export interface ExampleSchema extends Schema {
  paths: {
    'GET /': {
      request: {
        querystring: {
          name?: string;
        };
      };
      response: {
        200: {
          content: string;
        };
      };
    };
  };
}

const exampleService: Service<ExampleSchema> = {
  'GET /': (req, reply) => {
    // typescript will infer correct types for us
    const name = req.query.name ?? 'World';

    // Calling send directly is not allowed
    // reply.send(`Hello ${name}`)
    // Calling send with wrong payload will result in an error
    // reply.status(200).send(new Date())

    return reply.status(200).send(`Hello ${name}`);
  },
};

const app = fastify();
addSchema(app, {
  // it is strongly recommended to generate json schema to guaruntee runtime validity
  jsonSchema: {},
  service: exampleService,
});

// Start listening.
app.listen(3000, (err: any) => {
  if (err) {
    app.log.error(err);
    process.exit(1);
  }
});
```

复杂的例子可以找到 [排字测试](https://npmcn.com/package/%40coobaha/typed-fastify/test/typed-fastify.test-d.ts) 财务报告和审定财务报表 内 [综合. test.ts](https://npmcn.com/package/%40coobaha/typed-fastify/test/integration.test.ts)。 。 。 .

## JSON 计划生成

您可以通过使用 : `typed-fastify-schema` 或者说 `tfs` 弹匣

```sh
npx tfs gen
```

```
tfs gen [files]

Generates json schemas next to corresponding ts files

Positionals:
  files  glob pattern of files                               [string] [required]

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]
```

```sh
# it will generate example_schema.gen.json next to file
npx tfs gen example_schema.ts
```

生成 schema 时 - 直接传递到插件中以获得运行时间验证 QQ

```typescript
import jsonSchema from './example_schema.gen.json';

// ...

addSchema(app, {
  jsonSchema,
  service,
});
```

### 写作服务

1.  一个对象中的处理器 推论会很好用,你只是让TS开心 事情正在起作用
    
2.  处理器在不同的文件或单独的函数中 - 您需要用精确的处理器类型提示 TS .
    

```typescript
import { RequestHandler, Schema } from '@coobaha/typed-fastify';

interface MySchema extends Schema {}

const myHandler: RequestHandler<MySchema, 'GET /hello'>['AsRoute'] = (req, reply) => {};
```

3.  当您想要为多个交叉端点设置复杂的共享处理器( 共享相同) 道具)

```typescript
import { RequestHandler, Schema } from '@coobaha/typed-fastify';

interface MySchema extends Schema {}

const myHandlers: RequestHandler<MySchema, 'GET /hello' | `GET /hello2`>['AsRoute'] = (req, reply) => {};
```

4.  有时属性会不一样(例如从没有身体和POST会). 在此情况下, 您可能会被要求添加函数参数的类型

```typescript
import { RequestHandler, Schema } from '@coobaha/typed-fastify';

interface MySchema extends Schema {}

type MyHandlers = RequestHandler<MySchema, 'GET /hello' | `POST /hello`>;
const myHandlers = (req: MyHandlers['Request'], reply: MyHandlers['Reply']): MyHandlers['Return'] => {};

// if handler is async/await
const myHandlersAsync = async (req: MyHandlers['Request'], reply: MyHandlers['Reply']): MyHandlers['ReturnAsync'] => {};

addSchema(app, {
  jsonSchema: {},
  service: {
    'GET /hello': myHandlers,
    'GET /hello2': myHandlers,
  },
});
```

可能是TS无法推断 确切类型的复杂处理器 `addSchema` 所以你会 需要手动操作

```typescript
addSchema(app, {
  jsonSchema: {},
  service: {
    'GET /hello': myHandlers,
    'GET /hello2': myHandlers as RequestHandler<ExtendedSchema, 'GET /hello2'>['AsRoute'],
  },
});
```

### 注释类型

此库正在使用 [类型标注-json-schema](https://github.com/YousefED/typescript-json-schema) 带有自定义 变相为生相. 全体 `@tjs` [说明](https://github.com/YousefED/typescript-json-schema#annotations) 可用于微调计划输出

-   `@type` 可用于在使用后指定结束类型 `toJSON, toString` 类似对象的方法 `ObjectID` 从蒙戈DB
    
-   自从我们使用 `typejescript-json-schema`:所有已知的限制也都继承: - 记录没有正确转换,使用 `{ [k: string]: string }` 改为或提示 `@tjs`
    
-   [额外收益](https://json-schema.org/understanding-json-schema/reference/object#additionalproperties) 设定为 `false` 默认
    
    -   使用情况 `{ [k: string]: T }` 用于明确定义类型 `additionalProperties`
    -   或添加 `/** @additionalProperties true */` 允许任何东西的说明
    -   详情见:
        -   [默认为 AJV 选项](https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/#validator-compiler)
        -   [在 AJV 中删除附加](https://ajv.js.org/options.html#removeadditional)

## 常见问题

### @coobaha/typed-fastify 是什么？

用于粘贴的意见类型

### 如何安装 @coobaha/typed-fastify？

在项目目录运行 npm install @coobaha/typed-fastify，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：fastify（^4）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。它还提供命令行工具 tfs、typed-fastify-schema，可以用 npx tfs 直接运行。

### @coobaha/typed-fastify 支持 TypeScript 吗？

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

### @coobaha/typed-fastify 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @coobaha/typed-fastify 可以商用吗？

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

### @coobaha/typed-fastify 的下载量有多少？

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

### @coobaha/typed-fastify 还在维护吗？

最新版本 4\.1\.0 发布于 2025/11/05（1 年前）；至今共发布 36 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/02/19。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

