fastify / fastify/help

How to define type for decorator per plugin?

Open
#730 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

#### You have already researched for similar issues?
I've asked in Discord and Stackoverflow. There are no helpful replies so far.

#### What are you trying to achieve, or the steps to reproduce?

I would like to define types for two different decorators in two different plugins independently.

Here are two scopes A & B. The scope A must have a decorated field `utilA` and the same for the scope B.

```ts
// scope A
fastify.register((instance) => {
instance.decorate('utilA', 'AAA')
instance.get('/', (req, reply) => {
const data = instance.utilA // Property 'utilA' does not exist on type 'FastifyInstance<...>'
reply.send(data)
})
}, { prefix: '/A/' })

// scope B
fastify.register((instance) => {
instance.decorate('utilB', () => 'BBB')
instance.get('/', (req, reply) => {
const data = instance.utilB() // Property 'utilB' does not exist on type 'FastifyInstance<...>'
reply.send(data)
})
}, { prefix: '/B/' })
```

The only way I know to define decorators' types is a global extension of `FastifyInstance` object:

```ts
declare module 'fastify' {
interface FastifyInstance {
utilA: string
utilB: () => string
}
}
```

#### What was the result you received?
This statement makes accessible both `utilA` and `utilB` in *any* plugin.

#### What did you expect?
I need `utilA` be available to use in the scope A only and `utilB` in the scope B. Is there a way to define it separately?

#### Context

* *node version*: 16
* *fastify version*: 4.2.0
* *os*: Mac

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.