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

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

A Type Provider for json-schema-to-ts over Fastify

原始使用文档
文档目录7 节
  1. Install
  2. TypeScript requirements
  3. Plugin definition
  4. Setting FromSchema for the validator and serializer
  5. Using References in a Plugin Definition
  6. Example
  7. License

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

CI NPM version neostandard javascript style

A Type Provider for json-schema-to-ts

Install

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

TypeScript requirements

It is required to use [email protected] or above with strict mode enabled and noStrictGenericChecks disabled. You may take the following configuration (tsconfig.json) as an example:

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

Plugin definition

Note When using plugin types, withTypeProvider is not required to register the plugin.

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

Setting FromSchema for the validator and serializer

You can set the FromSchema settings for things like references and deserialization for the validation and serialization schema by setting ValidatorSchemaOptions and SerializerSchemaOptions type parameters. You can use the deserialize option in SerializerSchemaOptions to allow Date objects in place of date-time strings or other special serialization rules handled by fast-json-stringify.

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

Using References in a Plugin Definition

When defining a plugin, shared schema references and deserialization options can also be used with FastifyPluginAsyncJsonSchemaToTs and FastifyPluginCallbackJsonSchemaToTs.

Example

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

License

Licensed under MIT.

版本与发布记录

@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 是什么?

A Type Provider for json-schema-to-ts over Fastify

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