davidedantonio / fastify-axios

Add axios http client to your fastify instance
MIT License
39 stars 4 forks source link

Not working with TypeScript: Could not find a declaration file for module 'fastify-axios'. #31

Open honigkuchenbaer opened 1 year ago

honigkuchenbaer commented 1 year ago

I have installed this plugin according to the README with npm install fastify-axios.

But I can't require it as written in README. Instead I get the error:

import fastifyAxios from 'fastify-axios';
...
await server.register(fastifyAxios, {

[ERROR] 19:05:22 ⨯ Unable to compile TypeScript: src/index.ts(4,26): error TS7016: Could not find a declaration file for module 'fastify-axios'.

How can I use this plugin with TypeScript?

chiptoma commented 7 months ago

Just add the following index.d.ts in a folder named fastify-axios

E.g. /src/typings/declarations/fastify-axios/index.d.ts

/* eslint-disable unicorn/filename-case */

declare module 'fastify-axios' {
  import { FastifyPluginAsync } from 'fastify'
  import { AxiosRequestConfig, AxiosInstance } from 'axios'

  export type FastifyAxiosOptions = AxiosRequestConfig & {
    clients?: Record<string, AxiosRequestConfig>
  }

  const fastifyAxios: FastifyPluginAsync<FastifyAxiosOptions>

  // eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
  export interface FastifyAxiosDecorator {
    [key: string]: AxiosInstance
  }

  export default fastifyAxios

  module 'fastify' {
    interface FastifyInstance {
      axios: AxiosInstance & FastifyAxiosDecorator
    }
  }
}

Then add the path to your typeRoots inside the tsconfig.json

"compilerOptions": {
    "typeRoots": [
      "./src/typings/declarations/",
      "./node_modules/@types",
    ],
....
}

This will type fastify.axios as the global instance and any fastify.axios.AnyClientName instances

If you want to type it more strictly feel free to extend the FastifyAxiosDecorator like so:

// types.ts 

import 'fastify-axios'

import { AxiosInstance } from 'axios'

declare module 'fastify-axios' {
  interface FastifyAxiosDecorator {
    ClientName: AxiosInstance
  }
}
davidedantonio commented 7 months ago

@chiptoma Great work! Why don't you send a pull request? It would be nice to have typescript support on this Fastify plugin. 🙏