0

我已经按照文档进行了简单的打字稿设置

import fastify from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'
import http2 from 'http2'
import fs from 'fs'
import path from 'path'

function createRoutes(server: ServerInstance) {
  interface Query {
    foo?: number
  }

  interface Params {
    bar?: string
  }

  interface Body {
    baz?: string
  }

  interface Headers {
    a?: string
  }

  const opts: fastify.RouteShorthandOptions = {
    schema: {
      querystring: {
        type: 'object',
        properties: {
          foo: {
            type: 'number',
          },
        },
      },
      params: {
        type: 'object',
        properties: {
          bar: {
            type: 'string',
          },
        },
      },
      body: {
        type: 'object',
        properties: {
          baz: {
            type: 'string',
          },
        },
      },
      headers: {
        type: 'object',
        properties: {
          a: {
            type: 'string',
          },
        },
      },
    },
  }

  server.get<Query, Params, Headers, Body>(
    '/ping/:bar',
    opts,
    (request, reply) => {
      console.log(request.query) // this is of type Query!
      console.log(request.params) // this is of type Params!
      console.log(request.body) // this is of type Body!
      console.log(request.headers) // this is of type Headers!
      reply.code(200).send({ pong: 'it worked!' })
    },
  )
  return server
}

type ServerInstance = fastify.FastifyInstance<
  http2.Http2SecureServer,
  http2.Http2ServerRequest,
  http2.Http2ServerResponse
>

export async function createServer() {
  const server: ServerInstance = fastify({
    logger: true,
    http2: true,
    https: {
      allowHTTP1: true, // fallback support for HTTP1
      key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
      cert: fs.readFileSync(
        path.join(__dirname, '..', 'https', 'fastify.cert'),
      ),
    },
  })
  createRoutes(server)
  return server
}

但是,当使用 http2 类型时,类型不会被传递

在此处输入图像描述

像这样使用 HTTP1 类型

type ServerInstance = fastify.FastifyInstance<
  Server,
  IncomingMessage,
  ServerResponse
>

通过并正常工作

4

1 回答 1

1

使用

const opts: fastify.RouteShorthandOptions<
    http2.Http2SecureServer,
    http2.Http2ServerRequest,
    http2.Http2ServerResponse
>

作品。应该在 v3 中修复

于 2019-09-05T09:12:21.870 回答