下面是我的代码的简化版本:
npm install express express-cookies @types/cookie-session @types/express-sessionimport 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)
});在changeSession(req.session)上,我得到了错误:
Argument of type 'Session | undefined' is not assignable to parameter of type 'Session'.
Type 'undefined' is not assignable to type 'Session'当我使用app.get而不是router.get时,也会发生同样的情况。
不确定为什么express-cookie没有正确地将会话对象注册到请求。
下面是@types/cookie-session的链接:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/cookie-session/index.d.ts,它为express-cookies提供类型
有什么帮助吗?
发布于 2020-05-20 10:13:08
快捷饼干类型指定req.session可以是undefined。据我所知,只有在使用express注册req.session中间件时,才会定义cookieSession。因此,如果您出于任何原因不注册这个中间件(例如,删除错误注册它的代码),req.session将是未定义的。
因为会话中间件可能没有被注册,所以就类型而言,预期req.session可能是undefined是正确的。
因此,在使用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!)但这是不安全的。
发布于 2020-05-19 16:53:43
错误非常明显,express.Session可能是undefined,changeSession函数声明为Session类型的参数(而不是Session | undefined)。
如果您确信您的express.Session对象不会是undefined,则可以将默认参数值赋值如下
const changeSession = (session = express.Session!) => {
session.foo = 'bar'
}注意感叹号(!)在价值之后。它迫使编译器忘记undefined值。
这是相当棘手的,当然,如果这个express.Session是undefined,您可以结束运行时异常。
希望能帮上忙。
https://stackoverflow.com/questions/61892689
复制相似问题