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

标签 typescript typescript-typings hapi.js hapi

我有一个 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 错误“PluginProperties”类型上不存在属性“example”。

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

最佳答案

您需要扩展现有类型,然后最好将您的请求转换为它。

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

关于 typescript /Hapi : Property 'example' does not exist on type 'PluginProperties' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63224248/

相关文章:

javascript - 调用外部文件中声明的函数

typescript - 我如何决定 @types/* 是进入 `dependencies` 还是 `devDependencies` ?

typescript - 如何在 TypeScript 类型定义中简化定义长联合类型

typescript :如何为 npm 模块使用本地类型声明文件

javascript - hapi.js Cors Pre-flight 不返回 Access-Control-Allow-Origin header

azure - 验证错误: "tenantId" is not allowed when using AzureAD for hapi JS route authorization

javascript - 使用 javascript 的无限循环(Angular NgFor 和 http 请求)

angular - ts 找不到模块 '@angular/platform-browser' ;

plugins - 如何调用某些路由的Hapi插件?

typescript - 运行 "tsc"是检查 "node_modules"中的一个文件