TypeScript项目集成fastify-flash时request.flash方法类型报错
问题:Fastify + TypeScript项目中使用fastify-flash遇类型错误
调用request.flash方法时,TypeScript抛出以下错误:
Property 'flash' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>'.ts
项目配置代码(src/app.ts)
import type { FastifyCookieOptions } from '@fastify/cookie' fastify.register(import('@fastify/cookie'), { secret: 'my-secret', parseOptions: {} } as FastifyCookieOptions) fastify.register(import('@fastify/secure-session'), { secret: 'my-secret', salt: 'my-secret', cookie: { path: '/', httpOnly: true } }) fastify.register(import('@fastify/flash'))
使用request.flash的错误处理器代码
fastify.setErrorHandler(async function (error, request: FastifyRequest, reply: FastifyReply) { request.log.error(error) let errors = []; const locales = await fastify.getLocaleMsg(request.headers.lang as string || 'en'); if (error.statusCode === 429) { reply.code(429) error.message = locales.RATE_LIMIT_ERROR } if(error.code == 'FST_ERR_VALIDATION'){ reply.code(400) error.message = locales.VALIDATION_ERROR errors = error.validation ? error.validation.map((error) => locales[error.message as string] ? locales[error.message as string] : error.message ) : [] } request.flash('error', errors) error.message = error.message ? error.message : locales.SOMETHING_WENT_WRONG const accept = request.accepts() switch(accept.type(['json', 'html'])) { case 'json': reply.type('application/json').send({ msg: error.message , errors: errors }) break case 'html': reply.type('text/html').send(`<b>${locales.SOMETHING_WENT_WRONG}</b> <br /> ${error.message}`) break default: reply.send(Boom.notAcceptable('unacceptable')) break } // reply.send(error) })
解决方案
这个问题是TypeScript未识别到fastify-flash对FastifyRequest的类型扩展,按以下步骤解决:
确认类型依赖安装
执行命令确保类型定义正确安装:npm install @types/fastify-flash --save-dev # 或使用yarn yarn add @types/fastify-flash -D加载插件类型声明
在src/app.ts顶部添加类型导入,让TypeScript识别扩展:import '@fastify/flash'检查插件注册顺序
fastify-flash依赖@fastify/cookie或@fastify/secure-session,你的注册顺序(先注册cookie/secure-session,再注册flash)是正确的。如果仍有问题,可在插件就绪后再设置错误处理器:fastify.ready().then(() => { fastify.setErrorHandler(/* 你的错误处理器代码 */) })手动扩展类型(兜底方案)
创建src/types/fastify-flash.d.ts文件,手动声明类型:import { FastifyRequest } from 'fastify' declare module 'fastify' { interface FastifyRequest { flash(type: string, message: any): void flash(type: string): any[] } }并在
tsconfig.json中包含该文件:{ "include": ["src/**/*", "src/types/**/*"] }
内容的提问来源于stack exchange,提问作者Ravi Roshan
相关产品推荐
相关产品推荐

