TypeScript:使用自己的类扩展Express.Session接口 [英] TypeScript: Extend Express.Session interface with own class

查看:82
本文介绍了TypeScript:使用自己的类扩展Express.Session接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用npm包进行Typescript项目.我想向Express.Session接口添加一个属性.

I'm working on a Typescript project with npm packages. I want to add a property to the Express.Session interface.

示例类:

class User {
    name: string;
    email: string;
    password: string;
}

export = User;

用于接口定义的新d.ts文件(不想编辑express-session.d.ts):

New d.ts file for the interface definition (don't want to edit express-session.d.ts):

declare namespace Express {
    interface Session {
        user: User
    }
}

app.ts

import User = require('./User');

function (req: express.Request, res: express.Response) {
    req.session.user //I want to use it like this.
}

问题是,在d.ts文件中未知用户.但是既不需要也不导入用户文件修复程序.

the problem is, that User is not known in de d.ts file. But neither require nor import the User-file fixes that.

如何将自己的类添加到会话接口?

How can I add my own class to the session interface?

推荐答案

晚了一点,但是应该可以将界面导入到定义文件中

A bit late to the party, but it should be possible to import your interface to the definitions file

import { User } from '../models/user';

declare global {
  namespace Express {
    interface Session {
      _user?: User
    }
  }
}

这篇关于TypeScript:使用自己的类扩展Express.Session接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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