Fastify: How to call a decorate methods in typescript

Created on 29 Jan 2019  路  3Comments  路  Source: fastify/fastify

question

Most helpful comment

You will need to augment the fastify type definition, so typescript knows about the new property:

File: yourproject/@types/fastify/index.d.ts (if the compiler does not pick up your definitions file, add the location of the @types folder to typeRoots in your tsconfig.json)

import fastify from 'fastify';

declare module 'fastify' {
  export interface FastifyInstance<
    HttpServer = Server,
    HttpRequest = IncomingMessage,
    HttpResponse = ServerResponse,
  > {
    port: number;
  }
}

Read more about augmentation in the docs: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

A blog explaining the process in more detail: https://medium.com/car2godevs/fastify-with-typescript-production-ready-integration-2303318ecd9e

All 3 comments

I think you should be able to call them like you do in JavaScript. Could you please elaborate a little?

fastify.decorate('config',{
port:4000
})

in js fastify.config.port is possible

But in typescript fastify.config.port throw an error like property config is not present in Fastify instance

You will need to augment the fastify type definition, so typescript knows about the new property:

File: yourproject/@types/fastify/index.d.ts (if the compiler does not pick up your definitions file, add the location of the @types folder to typeRoots in your tsconfig.json)

import fastify from 'fastify';

declare module 'fastify' {
  export interface FastifyInstance<
    HttpServer = Server,
    HttpRequest = IncomingMessage,
    HttpResponse = ServerResponse,
  > {
    port: number;
  }
}

Read more about augmentation in the docs: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

A blog explaining the process in more detail: https://medium.com/car2godevs/fastify-with-typescript-production-ready-integration-2303318ecd9e

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rqbazan picture rqbazan  路  3Comments

rabbitooops picture rabbitooops  路  3Comments

avilang picture avilang  路  3Comments

PacoDu picture PacoDu  路  3Comments

jsumners picture jsumners  路  4Comments