本文介绍了如何向节点请求会话对象声明打字稿接口扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面,returnTo 通过我的通行证方法添加到会话对象中.我如何在打字稿中声明它的接口?

In the following, returnTo is added to the session object by my passport methods. How do I declare its interface in typescript?

import express = require('express');
import expressSession = require('express-session');

// how to declare presence of returnTo, which is not in underlying type?

export function createSession(req: express.Request, res: express.Response, next: Function) {

  passport.authenticate('local', (err: any, user: UserInstance, info: any) => {
    //. . .
    req.logIn(user, (err) => {
      //. . .
      res.redirect(req.session.returnTo || '/');
    });
  })(req, res, next);
};

推荐答案

express-session 在绝对类型上有一个类型声明:

There's a type declaration for express-session on DefinitelyTyped:

https://github.com/borisyankov/DefinitelyTyped/blob/master/express-session/express-session.d.ts

按照该文件中的模式,您可以创建一个新的 d.ts(随意命名),其中包含:

Following the pattern in that file, you can create a new d.ts (call it whatever you want) containing:

declare module Express {
  export interface Session {
    returnTo: string;
  }
}

TypeScript 会将这个额外的属性合并"到现有的定义中.

TypeScript will "merge" this extra property into the existing definitions.

这篇关于如何向节点请求会话对象声明打字稿接口扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:12