如何使用@types/express-session? [英] How to use @types/express-session?
问题描述
当我写这篇文章时:
import { Request } from 'express-serve-static-core';
router.post((req: Request, res, next) => {
req.session.user = user;
}
tsc
给我一个错误:
'对象可能是'未定义'.
'Object is possibly 'undefined'.
我知道原始 Request
类型没有 session
字段.
I know the original Request
type does not have the session
field.
我检查了 @types/express-session
index.d.ts
文件,发现这个:
I check @types/express-session
index.d.ts
file, found this:
declare global {
namespace Express {
interface Request {
session?: Session;
sessionID?: string;
}
//....
}
所以我想在 req
中添加额外的字段 session
和 sessionID
类型.
So I want to add extra field session
and sessionID
type to the req
.
我该如何使用?像这样: req: Request &ExpressSessionRequest
.
How can I use ? like this: req: Request & ExpressSessionRequest
.
因此 req
将具有原始 Request
类型和 @types/express-session
添加的额外字段类型.
So the req
will have both original Request
type and extra fields type which @types/express-session
add.
推荐答案
问题不在于 Request
没有 session
或 sessionID
> 属性 -- express-session
的类型已经通过 声明合并.
The problem is not that Request
does not have the session
or sessionID
properties -- the typings for express-session
already adds the properties to Request
interface via declaration merging.
错误来自打开 strictNullChecks
编译器选项.由于属性 session
在类型定义中被声明为可为空的,编译器会准确地警告您.如果您确定 req.session
不是未定义的空值,您可以使用 非空断言运算符 (!
) 抑制错误:
The error comes from turning the strictNullChecks
compiler option on. Since the properties session
is declared as nullable in the type definition, the compiler warns you exactly that. If you are sure that req.session
is not null of undefined, you can use the not-null assertion operator (!
) to suppress the error:
router.post((req: Request, res, next) => {
req!.session!.user = user;
})
或者显式检查 null|undefined:
Or check for null|undefined explicitly:
router.post((req: Request, res, next) => {
if (req.session) {
req.session.user = user;
}
})
<小时>
如果您想让 session
和 sessionID
属性不可为空,那么您可以编写自己的自定义类型:
If you want to make the session
and sessionID
properties non-nullable, then you can write your own custom type:
type YourSessionRequest = Request & {
session: Express.Session;
sessionID: string;
}
router.post((req: YourSessionRequest, res, next) => {
req.session.user = user;
})
这篇关于如何使用@types/express-session?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!