Typescript: object is possibly undefined
valdoryu opened this issue · comments
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Fastify version
3.25.3
Plugin version
4.1.1
Node.js version
16.13.1
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
12.1
Description
When trying to call fastify.mongo.db.collection, I get a warning from TS telling me db is possibly undefined
This forces me to override the type in every db call I make in the entire app
Steps to Reproduce
Hi, i'm using your package with typescript 4.5.4 configured with scrict mode
My registering:
instance.register(MongoDb, {
forceClose: true,
database: instance.config.MONGO_DB_NAME,
url: instance.config.MONGO_ENDPOINT,
})
I checked types and indeed, db has been declared with db?: DB
Expected Behavior
As stated by the doc, if we have a database string in plugin options or a mongo url containing the database name, you are sure to have a db property on fastify.mongo, therefore we should not need to override types everywhere in the app
cc @fastify/typescript
@ValdoGhafoor It's due to the fact that db
is undefined if you don't provide a database
option. Along with strict
option, you can use: ?
to supress this warning (fastify.mongo.db?.collection('users')
)
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Sorry to bring this back from the dead - by 'database' option do you mean specifying it in the connection string? I'm doing that and seeing the same issue.
This is a TS limitation: we are using type declaration merging to add types to the Fastify instance. We are open to new ideas, though.