簡體   English   中英

如何在不同的插件中分別輸入 Fastify 裝飾器?

[英]How to separately type Fastify decorators in different plugins?

我在兩個插件(范圍)中輸入裝飾器時遇到問題:

import Fastify, { FastifyInstance } from 'fastify'
const fastify = Fastify()

// 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/' })

我可以全局定義類型:

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

它解決了編譯器錯誤。 但由於utilAutilB是全局定義的,編譯器允許我在 scope A 中使用utilB ,反之亦然。

有沒有辦法按照 scope 獨立地做同樣的事情?

不,由於 TypeScript 的工作方式,我認為使用declare module ''語法是不可能的(盡管比我聰明的人可能能夠弄清楚如何)。

您可以做的一件事是使用您的新屬性創建FastifyInstance的子類型(它們需要是可選的,否則 TypeScript 可能會根據您的 tsconfig 設置對您生氣)並使用該類型鍵入您的插件 fastify 實例。 例如:

// Scope A
import { FastifyInstance } from 'fastify';

type MyPluginsFastifyInstance = FastifyInstance & { myThing?: MyType; }

export default async (fastify: MyPluginFastifyInstance) => {
  ... // Implementation.
  fastify.myThing // TypeScript is happy :)
}

// Scope B
export default async (fastify) => {
  fastify.myThing // TypeScript is mad at you >:(
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM