我有 some models , 如:
import * as Sequelize from 'sequelize'; // !
export interface UserAttributes {
id?: number;
email?: string;
googleToken?: string;
}
export interface UserInstance extends Sequelize.Instance<UserInstance, UserAttributes>, UserAttributes {
}
export interface UserModel extends Sequelize.Model<UserInstance, UserAttributes> {
}
// ... model definition
我需要使用 import 语句来使用泛型
Sequelize.Instance<TInstance, TAttributes>
我编写了一些中间件来将用户实例添加到请求对象(或 req.session 对象,不满足)
那我需要typescript to know我的新扩展,为此我有文件 src/_extra.ts 内容:
/// <reference path="./models/db.ts" /> -- also does not work
declare namespace Express {
export interface Request {
oauthClient: Googleapis.auth.OAuth2; // Googleapis is namespace
user?: UserInstance; // or ContactsProject.Models.UserInstance;
}
export interface Session {/* ... some same */}
}
我需要导入我的 用户实例 从我的模型文件中输入。导入会破坏我所有的 _extra 命名空间定义,在命名空间内我不能使用导入。
我已经尝试创建命名空间 ContactsProject,但我遇到了同样的问题:如果我使用导入, typescript 看不到我的命名空间,如果我没有,我无法定义我的 UserInstance 类型。
Sequelize 不声明命名空间。
我只想在我的命名空间中导入一些泛型类型。
我使用 typescript 版本 2.0.3。
最佳答案
当您使用 import
文件中的语句,TypeScript 将其视为一个模块。因此,您在其中声明的任何 namespace 都不再是全局的,而是该模块的本地名称。
导入您的接口(interface),然后将命名空间声明包装在 declare global { ... }
中.
关于node.js - 使用 typescript 2 使用 sequelize 模型扩展 express 请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40094255/