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

Viewed 672

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?

2 Answers

You need to extend the existing type and then ideally cast your Request to it.

import { PluginProperties } from '@hapi/hapi';

interface IExtendedPluginProperties extends PluginProperties {
  example: {
    key: any; // define your strict types here instead of `any`
  }
};

Then inside your handler...

async handler(request: Request, h: ResponseToolkit) {
  const { key } = (<IExtendedPluginProperties>request.server.plugins).example;
}

PS. The accepted answer is wrong, what Andrej Leitner is suggesting is literally overriding the existing Hapi types. When you update to newest version of Hapi this will be gone or inaccurate. You should never override, use extend instead.

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
  }
}
Related