@fastify/type-provider-json-schema-to-ts

中文文档
5.0.1发布于 2026/10/10MITTypeScriptCommonJS构建来源已验证近 30 天下载 41.1万

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

中文使用文档
文档目录7 节
  1. 安装
  2. 类型脚本要求
  3. 插件定义
  4. 为验证器和序列器设置 FromSchema
  5. 在插件定义中使用引用
  6. 示例
  7. 许可证

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

CI NPM version neostandard javascript style

类型提供者 json-schema-to-ts (日语)

安装

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

类型脚本要求

它必须使用 [email protected] 或以上为 strict 模式已启用 noStrictGenericChecks 已禁用。 您可选择以下配置( E)tsconfig.json例如:

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

插件定义

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

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 财务报告和审定财务报表 deserialization 通过设置验证和序列化计划 ValidatorSchemaOptions 财务报告和审定财务报表 SerializerSchemaOptions 类型参数. 你可以用这个 deserialize 选项在 SerializerSchemaOptions 日期对象取代日期字符串或其他特殊序列规则 快速字符串。 。 。 .

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。 。 。 .

示例

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()
};

许可证

许可证根据 麻省理工学院。 。 。 .

版本与发布记录

@fastify/type-provider-json-schema-to-ts 共发布 14 个版本,首次发布于 2021/12/09;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.0.1latest2026/10/101 个月前
5.0.02024/12/231.9 年前
4.0.12024/11/122 年前
4.0.0next2024/09/052 年前
4.0.0-pre.fv5.12024/07/022 年前
3.0.02024/01/242 年前

关于 @fastify/type-provider-json-schema-to-ts 的常见问题

@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 和提交记录判断。