我有一个 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/