0

I'm using the fastify package where type definitions depend on the configuration options you set for it (for example whether you create http or http2 server). I would like to retain these dynamic types in files that the fastify calls (for example a file that registers routes).

// loader.ts
import fastify from 'fastify';
import registerApiRoutes from './registerApiRoutes';

export default function loader() {
  return fastify({
    http2: true,
  })
  .register(registerApiRoutes)
  .listen();
}

// registerApiRoutes
export default function registerApiRoutes(fastify) {
  fastify
    .get(...);
    .post(...);
}

How would I achieve that the "fastify" parameter in "registerApiRoutes.ts" has the correct type depending on what settings I chose in "loader.ts"?

sergiz
  • 151
  • 1
  • 6

1 Answers1

0

Use Conditional Types.

Example:

interface FastifyConfiguration {
  http2: boolean
}

interface Fastify {
  get(): void
  post(): void
}

interface Http2Fastify extends Fastify {
  http2Only(): void
}

interface Http1Fastify extends Fastify {
  http1Only(): void
}

declare function fastify<C extends FastifyConfiguration>(conf: C): C['http2'] extends true ? Http2Fastify : Http1Fastify
Rubydesic
  • 3,386
  • 12
  • 27