undefined' is not assignable to parameter of type 'Session'

问题描述 投票:0回答:1

Here's a simplified version of my code:

npm install express express-cookies @types/cookie-session @types/express-session
import express from express();
import cookieSession from 'cookie-session';


const app = express();

app.use(cookieSession({
    name: 'session',
    keys: [
        process.env.SESSION_KEY as string
    ]
}));

const router = express.Router();

const changeSession = (session = express.Session) => {
    session.foo = 'bar'
}

router.get((req, res) => {
    changeSession(req.session)
});

On changeSession(req.session) I get the error:

Argument of type 'Session | undefined' is not assignable to parameter of type 'Session'.
  Type 'undefined' is not assignable to type  'Session'

Same happens when I use app.get instead of router.get

Not sure why express-cookies isn't registering the session object to the request properly.

Here's a link to @types https:/github.comDefinitelyTypedDefinitelyTypedblobmastertypescookie-sessionindex.d.ts。 它为 express-cookies

有什么帮助吗?

express typescript-typings express-session
1个回答
0
投票

express-cookies的输入指定了 req.session 可以 undefined. 据我所知 req.session 只有当您注册了 cookieSession 中间件与express。所以,如果因为任何原因你不会注册这个中间件(例如,删除误注册它的代码)。req.session 将是未定义的。

因为会话中间件有可能没有被注册,所以从类型上来说,正确的做法是期待 req.sessionundefined.

所以,使用TS,你需要检查是否是 req.session 的定义,然后再对其进行操作。

if (req.session) {
    changeSession(req.session)
}

或者如果路由的会话是强制性的,则明确地抛出一个错误。

if (!req.session) {
    throw new Error('Session is missing.');
}

changeSession(req.session)

或者,作为最后的手段,使用感叹号告诉TS: req.session 实际上是被定义的。

changeSession(req.session!)

但这不是类型安全的。


0
投票

这个错误是很明确的。express.SessionundefinedchangeSession 函数被声明为期待一个类型为 Session (不是 Session | undefined).

如果你确定你的 express.Session 对象不会 undefined你可以像这样分配默认参数值。

const changeSession = (session = express.Session!) => {
    session.foo = 'bar'
}

请注意感叹号(!)的值后。它迫使编译器忘记 undefined 值。这是相当棘手的,当然,你可能最终会出现运行时异常,如果这个 express.Sessionundefined.

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.