属性 'db' 在类型"FastifyInstance<Server 上不存在



//util文件

async function dbconnector(fastify, options) {
try {
await client.connect()
console.log('db connected succesfully')
fastify.decorate('db', { client })
} catch(err) {
console.error(err)
}
}
module.exports = fastifyPlugin(dbconnector)

//索引文件

const dbconnector = require('./utils/db')
fastify.register(dbconnector)

每当我尝试执行fastify.db时,它都会显示以下错误

类型"FastifyInstance<"上不存在属性"db";服务器,IncomingMessage,ServerResponse,FastifyLoggerInstance>amp;PromiseLike

按照Fastify设置其类型的方式,您需要自己将装饰器添加到FastifyInstance中。你可以这样做:

import { FastifyLoggerInstance, FastifyPluginAsync, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault } from 'fastify'
declare module 'fastify' {
export interface FastifyInstance<
RawServer extends RawServerBase = RawServerDefault,
RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,
RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,
Logger = FastifyLoggerInstance
> {
db: FastifyPluginAsync;
}
}

如果您还没有在tsconfig.json中设置该类型文件,则需要告诉typescript拾取该类型文件。这样做的一个例子是:

{
"compilerOptions": {
// ... your other config
"typeRoots": [
"types"
]
},
// ... the rest of your config
}

然后将配置保存在types/index.d.ts下的项目根目录中。

这告诉typescript编译器您已经在该文件中定义了自己的类型。扩展FastifyInstance以包含装饰器现在应该可以工作了。

相关内容

最新更新