Typescript/Hapi: 属性 'example' 在类型 'PluginProperties' 上不存在

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

我有一个 hapi 插件,如下所示:

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

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

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

我可以看到该插件在路由处理程序中公开,但是当我尝试使用以下方法访问该值时:

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

我有一个打字稿错误Property 'example' does not exist on type 'PluginProperties'.

如何将此插件和其他插件添加到 hapi 类型?

您可以通过扩展 types/hapi/index 中的 hapi 模块来定义 PluginProperties 字段和类型。d.ts:

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

您需要扩展现有类型,然后理想地将您的 Request 投射到它。

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

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

然后在你的处理程序中...

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

PS。接受的答案是错误的,Andrej Leitner 所暗示的是字面上覆盖现有的 Hapi 类型。当您更新到最新版本的 Hapi 时,这将消失或不准确。您永远不应该覆盖,而是使用 extend