typescripttypescript-typingshapi.jshapi

Typescript/Hapi: Property 'example' does not exist on type 'PluginProperties'


Ii I have a hapi plugin such as the one below:

exports.plugin = {
    name: 'example',
    register: function (server, options) {

        server.expose('key', 'value');

        console.log(server.plugins.example.key);      // 'value'
    }
};

I can see that the plugin is exposed in a route handler, however when I try to access that value using:

async handler(request: Request, h: ResponseToolkit) {
      const value = request.server.plugins.example.key;

I have a typescript error Property 'example' does not exist on type 'PluginProperties'.

How do I add this and other plugins to the hapi type?


Solution

  • You can define PluginProperties fields and types by extending hapi module in types/hapi/index.d.ts:

    declare module 'hapi' {
      export interface PluginProperties {
        [key: string]: any; // TODO define
      }
    }