@coobaha/typed-fastify

中文文档
4.1.0发布于 2025/11/05MITTypeScriptCommonJS近 30 天下载 1万

opinionated types for fastify

原始使用文档
文档目录4 节
  1. Usage
  2. JSON schema generation
  3. Writing service
  4. Annotating types

Typed Fastify

Build Status Coverage Status NPM Version

Online docs

This package adds strong TypeScript support to Fastify request handlers and enforces handlers to have typed schema which is used to validate request params and replies. From this schema it does two things:

  • static typechecking against TypeScript Schema
    • request.body
    • request.headers
    • request.querystring
    • request.params
    • route.path.params are also inferred and mapped to request.params, it is also not possible to make a typo in schema params
    • reply is always based on status, developer won't be able to use plain reply.send() but forced to explicitly set status first, based on which response type will be inferred
  • JSON schema generation from TS Schema (using typescript-json-schema with custom transforms, all @tjs annotations can be used to fine-tune output)
    • since we use typejescript-json-schema: all known limitations of lib are inherited:
      • Records are not transformed correctly, use { [k: string]: string } instead or hint with @tjs
  • Runtime validation using generated JSON schema (optional but strongly recommended as it brings extra safety to runtime and ensures that code assumptions about data are correct)

demo video

Usage

npm i @coobaha/typed-fastify

pnpm i @coobaha/typed-fastify

yarn add @coobaha/typed-fastify

Example of service we want to build

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

Simple implementation without schema generation will be following

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

Complex examples can be found typescript tests and in integration.test.ts.

JSON schema generation

You can generate json schema from your TS types by using typed-fastify-schema or tfs bins

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]
# it will generate example_schema.gen.json next to file
npx tfs gen example_schema.ts

When schema is generated - just pass it to plugin to have runtime validations 🎉

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

// ...

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

Writing service

  1. Handlers in one object Type inference will work nicely in this case, you just make TS happy and things are working 🥳

  2. Handlers in a different file or separate functions - you will need to hint TS with exact type of handler.

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

interface MySchema extends Schema {}

const myHandler: RequestHandler<MySchema, 'GET /hello'>['AsRoute'] = (req, reply) => {};
  1. When you want to have complex shared handler for multiple endpoints that intersect (share same props)
import { RequestHandler, Schema } from '@coobaha/typed-fastify';

interface MySchema extends Schema {}

const myHandlers: RequestHandler<MySchema, 'GET /hello' | `GET /hello2`>['AsRoute'] = (req, reply) => {};
  1. Sometimes properties won't be the same (for instance GET never has body and POST will). In this case you will probably be asked to add types to function params
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,
  },
});

It might be that TS can't infer exact type of complex handler when passed to addSchema so you'll need to do it manually

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

Annotating types

This library is using typescript-json-schema with custom transforms for schema generation. All @tjs annotations can be used to fine-tune schema output

  • @type can be used to specify end type after using toJSON, toString methods of objects like ObjectID from MongoDB

  • since we use typejescript-json-schema: all known limitations are also inherited: - Records are not transformed correctly, use { [k: string]: string } instead or hint with @tjs

  • additionalProperties are set to false by default

版本与发布记录

@coobaha/typed-fastify 共发布 36 个版本,首次发布于 2021/02/19;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.1.0latest2025/11/051 年前
4.0.02025/10/061.1 年前
3.0.02024/10/192 年前
2.3.02024/04/012 年前
2.2.02024/03/172 年前
2.1.42024/03/072 年前

关于 @coobaha/typed-fastify 的常见问题

@coobaha/typed-fastify 是什么?

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