
[英]Next Js & Typescript - Property setState does not exist on type Example
[英]Typescript/Hapi: Property 'example' does not exist on type 'PluginProperties'
Ii 我有一个 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 错误Property 'example' does not exist on type 'PluginProperties'.
如何将此插件和其他插件添加到 hapi 类型?
您可以通过在types/hapi/index.d.ts中扩展 hapi 模块来定义 PluginProperties 字段和类型:
declare module 'hapi' {
export interface PluginProperties {
[key: string]: any; // TODO define
}
}
您需要扩展现有类型,然后理想地将您的请求转换为它。
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.