我已经按照文档进行了简单的打字稿设置
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
>
通过并正常工作