node.js - 使用 typescript 2 使用 sequelize 模型扩展 express 请求对象

标签 node.js express typescript namespaces sequelize.js

我有 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/

相关文章:

javascript - 在 Node 中获取 header 重新发送错误

node.js - 全新安装后重建时 Ember CLI 崩溃——我做错了什么?

node.js - 尝试使用 SAS 访问 Azure blob 时收到 "Signature did not match. String to sign used was..."

node.js - Heroku Node.js RedisCloud Redis::CannotConnectError 在本地主机上而不是 REDISCLOUD_URL

javascript - 将组件传递给声明或指令有什么区别?

javascript - 如何为 Angular 2 设置 gulp-typescript?

javascript - Mongoose.js 通过一个 connect() 调用创建到 MongoDB 的多个连接

node.js - 如何在express js中使用特定字段而不是id进行查询

javascript - 更新和/或修复 AppFog 数据库的模式

angular - Ionic 3 Tabs 初始化后不刷新