網站搜尋

Typescript/Hapi:屬性 'example' 在類型 '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;

我有一個 TypeScript 錯誤 屬性 'example' 在類型 'PluginProperties' 上不存在。

我如何將這個以及其他插件加入 hapi 類型?

答案#1

你需要擴展現有的類型,然後理想情況下將你的請求轉型為它。

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

附註:被接受的答案是錯的,Andrej Leitner 所建議的做法實際上是覆蓋現有的 Hapi 類型。當你更新到最新版本的 Hapi 時,這將消失或不準確。你永遠不應該覆蓋,應該使用 extend 代替。

答案#2

您可以透過在 types/hapi/index.d.ts 擴展 hapi 模組來定義 PluginProperties 欄位和類型:

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