# @fastify/type-provider-json-schema-to-ts 中文文档

规范地址：https://npmcn.com/package/%40fastify/type-provider-json-schema-to-ts/

版本：5\.0\.1
npm 元数据更新时间：2026-10-10T10:15:15.060Z
中文译文更新时间：2026-11-14T11:20:17.941Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40fastify/type-provider-json-schema-to-ts
原文对照：https://npmcn.com/package/%40fastify/type-provider-json-schema-to-ts/?lang=original
项目主页：https://github.com/fastify/fastify-type-provider-json-schema-to-ts#readme
源码仓库：https://github.com/fastify/fastify-type-provider-json-schema-to-ts

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

- 包体积（解压后）：30.9 kB，16 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2021-12-09T13:09:57.351Z
- 最新版本发布：2026-10-10T10:15:14.718Z
- 近 30 天下载量：410678（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：14（近 12 个月 1 个）

## 中文简介

Json- schema- 至 ts 的快取类型提供者

## 安装

```sh
npm install @fastify/type-provider-json-schema-to-ts
```

也可以使用：`pnpm add @fastify/type-provider-json-schema-to-ts`、`yarn add @fastify/type-provider-json-schema-to-ts`、`bun add @fastify/type-provider-json-schema-to-ts`

## README

# @ fastify/type-productor-json-schema-to-ts (英语)

[![CI](https://github.com/fastify/fastify-type-provider-json-schema-to-ts/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-type-provider-json-schema-to-ts/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/type-provider-json-schema-to-ts.svg?style=flat)](https://www.npmjs.com/package/@fastify/type-provider-json-schema-to-ts) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

类型提供者 [json-schema-to-ts (日语)](https://github.com/ThomasAribart/json-schema-to-ts)

## 安装

```bash
npm i @fastify/type-provider-json-schema-to-ts
```

## 类型脚本要求

它必须使用 `TypeScript@4.3` 或以上为 [`strict`](https://www.typescriptlang.org/tsconfig/#strict) 模式已启用 [`noStrictGenericChecks`](https://www.typescriptlang.org/tsconfig/#noStrictGenericChecks) 已禁用。 您可选择以下配置( E)`tsconfig.json`例如:

```json
{
  "compilerOptions": {
    "strict": true,
    "noStrictGenericChecks": false
  }
}
```

## 插件定义

> **说明** 当使用插件类型时, `withTypeProvider` 不需要注册插件.

```ts
const plugin: FastifyPluginAsyncJsonSchemaToTs = async function (
  fastify,
  _opts
) {
  fastify.get(
    "/",
    {
      schema: {
        body: {
          type: "object",
          properties: {
            x: { type: "string" },
            y: { type: "number" },
            z: { type: "boolean" },
          },
          required: ["x", "y", "z"],
        } as const,
      },
    },
    (req) => {
      // The `x`, `y`, and `z` types are automatically inferred
      const { x, y, z } = req.body;
    }
  );
};
```

## 为验证器和序列器设置 FromSchema

你可以设置 `FromSchema` 诸如此类的设置 [`references`](https://github.com/ThomasAribart/json-schema-to-ts#references) 财务报告和审定财务报表 [`deserialization`](https://github.com/ThomasAribart/json-schema-to-ts#deserialization) 通过设置验证和序列化计划 `ValidatorSchemaOptions` 财务报告和审定财务报表 `SerializerSchemaOptions` 类型参数. 你可以用这个 `deserialize` 选项在 `SerializerSchemaOptions` 日期对象取代日期字符串或其他特殊序列规则 [快速字符串](https://github.com/fastify/fast-json-stringify?tab=readme-ov-file#specific-use-cases)。 。 。 .

```ts
const userSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    givenName: { type: "string" },
    familyName: { type: "string" },
  },
  required: ["givenName", "familyName"],
} as const satisfies JSONSchema;

const sharedSchema = {
  $id: "shared-schema",
  definitions: {
    user: userSchema,
  },
} as const satisfies JSONSchema;

const userProfileSchema = {
  $id: "userProfile",
  type: "object",
  additionalProperties: false,
  properties: {
    user: {
      $ref: "shared-schema#/definitions/user",
    },
    joinedAt: { type: "string", format: "date-time" },
  },
  required: ["user", "joinedAt"],
} as const satisfies JSONSchema


type UserProfile = FromSchema<typeof userProfileSchema, {
  references: [typeof sharedSchema]
  deserialize: [{ pattern: { type: "string"; format: "date-time" }; output: Date }]
}>;

// Use JsonSchemaToTsProvider with shared schema references
const fastify = Fastify().withTypeProvider<
  JsonSchemaToTsProvider<{
    ValidatorSchemaOptions: { references: [typeof sharedSchema] }
    SerializerSchemaOptions: {
      references: [typeof userProfileSchema]
      deserialize: [{ pattern: { type: "string"; format: "date-time" }; output: Date }]
    }
  }>
>()

fastify.get(
  "/profile",
  {
    schema: {
      body: {
        type: "object",
        properties: {
          user: {
            $ref: "shared-schema#/definitions/user",
          },
        },
        required: ['user'],
      },
      response: {
        200: { $ref: "userProfile#" },
      },
    } as const,
  },
  (req, reply) => {
    // `givenName` and `familyName` are correctly typed as strings
    const { givenName, familyName } = req.body.user;

    // Construct a compatible response type
    const profile: UserProfile = {
      user: { givenName: "John", familyName: "Doe" },
      joinedAt: new Date(), // Returning a Date object
    };

    // A type error is surfaced if profile doesn't match the serialization schema
    reply.send(profile)
  }
)
```

## 在插件定义中使用引用

在定义插件时,也可以使用共享的 schema 引用和去区域化选项 `FastifyPluginAsyncJsonSchemaToTs` 财务报告和审定财务报表 `FastifyPluginCallbackJsonSchemaToTs`。 。 。 .

### 示例

```ts
const schemaPerson = {
  $id: "schema:person",
  type: "object",
  additionalProperties: false,
  properties: {
    givenName: { type: "string" },
    familyName: { type: "string" },
    joinedAt: { type: "string", format: "date-time" },
  },
  required: ["givenName", "familyName"],
} as const satisfies JSONSchema;

const plugin: FastifyPluginAsyncJsonSchemaToTs<{
  ValidatorSchemaOptions: { references: [typeof schemaPerson] }
  SerializerSchemaOptions: {
    references: [typeof schemaPerson]
    deserialize: [{ pattern: { type: "string"; format: "date-time" }; output: Date }]
  };
}> = async function (fastify, _opts) {
  fastify.addSchema(schemaPerson)

  fastify.get(
    "/profile",
    {
      schema: {
        body: {
          type: "object",
          properties: {
            user: {
              $ref: "schema:person",
            },
          },
          required: ['user'],
        },
        response: {
          200: { $ref: "schema:person" },
        },
      }, // as const satisfies JSONSchema is not required thanks to FastifyPluginAsyncJsonSchemaToTs
    },
    (req, reply) => {
      // `givenName`, `familyName`, and `joinedAt` are correctly typed as strings and validated for format.
      const { givenName, familyName, joinedAt } = req.body.user;

      // Send a serialized response
      reply.send({
        givenName: "John",
        familyName: "Doe",
        // Date objects form DB queries can be returned directly and transformed to string by fast-json-stringify
        joinedAt: new Date(),
      })
    }
  )
}

const callbackPlugin: FastifyPluginCallbackJsonSchemaToTs<{
  ValidatorSchemaOptions: { references: [typeof schemaPerson] }
  SerializerSchemaOptions: {
    references: [typeof schemaPerson]
    deserialize: [{ pattern: { type: "string"; format: "date-time" }; output: Date }]
  };
}> = (fastify, options, done) => {
  // Type check for custom options
  expectType<string>(options.optionA)

  // Schema is already added above
  // fastify.addSchema(schemaPerson);

  fastify.get(
    "/callback-profile",
    {
      schema: {
        body: {
          type: "object",
          properties: {
            user: { $ref: "schema:person" },
          },
          required: ["user"],
        },
        response: {
          200: { $ref: "schema:person" },
        },
      },
    },
    (req, reply) => {
      const { givenName, familyName, joinedAt } = req.body.user

      reply.send({
        givenName,
        familyName,
        joinedAt: new Date(),
      });
    }
  );

  done()
};
```

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/type-provider-json-schema-to-ts/LICENSE)。 。 。 .

## 常见问题

### @fastify/type-provider-json-schema-to-ts 是什么？

Json- schema- 至 ts 的快取类型提供者

### 如何安装 @fastify/type-provider-json-schema-to-ts？

在项目目录运行 npm install @fastify/type-provider-json-schema-to-ts，或使用 pnpm add / yarn add / bun add。

### @fastify/type-provider-json-schema-to-ts 支持 TypeScript 吗？

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

### @fastify/type-provider-json-schema-to-ts 支持 ESM 还是 CommonJS？

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

### @fastify/type-provider-json-schema-to-ts 可以商用吗？

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

### @fastify/type-provider-json-schema-to-ts 的下载量有多少？

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

### @fastify/type-provider-json-schema-to-ts 还在维护吗？

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

