【发布时间】:2020-09-19 04:28:49
【问题描述】:
我在 TypeScript 中使用 Sequelize 在 Express 中实现 API。在使用关联 mixin 返回的值时,我遇到了与类型相关的错误。
这是我定义的数据模型的一部分:
export class User extends Model {
id!: number;
username!: string;
email!: string;
password!: string;
active!: boolean;
createdAt!: Date;
updatedAt!: Date;
}
export class UserSession extends Model {
token!: string;
userId!: number;
expiresAt!: Date;
renewalHours!: number;
getUser!: BelongsToGetAssociationMixin<User>;
}
这是我在会话期间(在 Express 中间件中)尝试验证请求的方式:
UserSession.findOne({ where: { token: req.body.token }, include: [User] })
.then(session => {
if (session) {
const now = moment();
if (session.expiresAt > now.toDate()) {
session.set('expiresAt',
now.add(session.renewalHours, 'hours').toDate());
session.save();
req.user = session.getUser();
next();
} else {
session.destroy();
res.status(400).json({ msg: 'Session expired' });
}
} else {
res.status(403).json({ msg: 'Not logged in' });
}
});
我已通过UserSession.belongsTo(User) 将UserSession 与User 关联(省略详细信息)。
特定的行
req.user = session.getUser();
从 TypeScript 产生以下错误:
Type 'Bluebird<User>' is missing the following properties from type 'User': id, username, email, password, and 26 more.
req 是 Express Request。我添加了一个 user 字段(用于 TypeScript),如下所示:
declare global {
namespace Express {
export interface Request {
user?: User;
session?: UserSession;
}
}
}
我知道 Sequelize 现在是基于 Bluebird Promise 框架构建的,所以我怀疑这与我的类型定义有关。似乎 TypeScript 不认为 UserSession.getUser 会返回带有 User 属性的东西。为什么不呢?
【问题讨论】:
标签: node.js typescript types sequelize.js