如何使用声明合并来声明其他属性?不覆盖模块? [英] How to declare additional properties using declaration merging? Without overwriting the module?

查看:79
本文介绍了如何使用声明合并来声明其他属性?不覆盖模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在使用 express-session,从定义类型 (@types/express-session) 输入

Well I am using express-session, with the typing from definity types (@types/express-session)

我注意到会话字段中的自定义数据类型没有任何内容.这不是那么有用.我希望将其扩展为包含(例如)userId: number.

I notice that the types don't have anything for custom data in the session fields. Which is not that useful. I wish to extend this to contain (say) userId: number.

文件 @types/express-session 显示它可以使用:

The file @types/express-session show it can be done using:

/**
 * This interface allows you to declare additional properties on your session object using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
 *
 * @example
 * declare module 'express-session' {
 *     interface SessionData {
 *         views: number;
 *     }
 * }
 *
 */

所以我创建了一个名为 ./src/types/types.ts 的文件,并将以下内容放入其中:

So I created a file named ./src/types/types.ts And put the following in it:

 declare module 'express-session' {
     interface SessionData {
         userId: number;
     }
 }

这个有效",在那个打字稿中现在看到了正确的字段.另一方面,由 express-sesion 公开的所有其他内容不再可见,因为 typescript 不再考虑其他模块定义部分.import {Session} from express-session"; 之类的东西现在给出错误:

This "works", in that typescript now sees the correct field. On the other hand everything else exposed by express-sesion is no longer visible, as typescript no longer considers the other module-definition part. Things like import {Session} from "express-session"; now give the error:

TS2305: Module '"express-session"' has no exported member 'Session'.

那么我如何扩展模块定义?

So how do I extend module definitions?

推荐答案

除了 @David_46592 方法之外,您还可以在自定义的 Context 中自定义您自己的请求类型.

Beside @David_46592 method, you can also customise your own request type within a customised Context.

例如,您要添加属性 UserId.可以通过以下方式完成.

For example, you want to add property UserId. It can be done with the following.

    import { Connection, EntityManager, IDatabaseDriver } from "@mikro-orm/core";
    import { Request, Response } from "express";
    
    export type MyContext = {
      em: EntityManager<any> & EntityManager<IDatabaseDriver<Connection>>;
      req: Request & { session: { userId?: number } };
      res: Response;
    };

然后只需在 app.tsindex.ts 中导入 MyContext 并在创建服务器时使用它,如下所示:

Then just import MyContext in your app.ts or index.ts and use it when you create server as below:

     const apolloServer = new ApolloServer({
        schema: await buildSchema({
          resolvers: [Resolvers...],
          validate: false,
        }),
        context: ({ req, res }): MyContext => ({ em: orm.em, req, res }),
      });

这篇关于如何使用声明合并来声明其他属性?不覆盖模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆