【问题标题】:How do I extend the typings of Express.Application to give typings for app.locals如何扩展 Express.Application 的类型以提供 app.locals 的类型
【发布时间】:2022-04-28 07:02:18
【问题描述】:

在我们的应用程序中,我们向中间件中使用的 app.locals 添加了很多配置对象。

const app = Express();
app.locals = {
  someConfig: config
}

我们目前有可以正常工作的 Request 对象的自定义类型

declare namespace Express {
  export interface Request {
    featureFlags?: FeatureFlag;
  }
}

我知道locals 来自 Express.Application,所以我尝试了这个,但它不起作用。

declare namespace Express {
  export interface Application {
    locals: {
      someConfig: config;
    };
  }

  export interface Request {
    featureFlags?: FeatureFlag;
  }
}

有没有人成功地将类型添加到 app.locals 中?

【问题讨论】:

  • 你有没有想过这个问题?

标签: typescript express


【解决方案1】:

您可以转到 node_modules/@types/express-serve-static-core/index.d.ts 中的原始文件声明,而不是使用新的声明文件。 并搜索应用程序界面。 诀窍是在该接口上定义另一个属性,您的所有路由都可以访问它,类似于 locals 属性。

  export interface Application<
    Locals extends Record<string, any> = Record<string, any> 
> extends EventEmitter, IRouter, Express.Application {
    //Make sure to keep all the others properties on the interface
    locals: Locals 
    db: mongoDb.Db //Here is the db key I've added, and all my routes can access it, just like the locals property.

 ];
}

现在您可以使用 app.db ="whatever you need" 为该属性分配一个值,并具有所有自动完成功能。 在您的路由处理程序或中间件中,您可以使用req.app.db 访问它。

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    相关资源
    最近更新 更多