簡體   English   中英

使用打字稿2使用sequelize模型擴展表達請求對象

[英]extend express request object with sequelize model using typescript 2

我有一些模型 ,例如:

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對象,不兼容

然后,我需要打字稿來了解我的新擴展名,為此,我擁有內容為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 */}
}

我需要從模型文件中導入UserInstance類型。 導入破壞了我所有的_extra命名空間定義,在命名空間內部我無法使用導入。 我曾嘗試創建命名空間ContactsProject ,但是遇到了同樣的問題:如果使用import ,打字稿看不到我的命名空間,否則,我無法定義UserInstance類型。 Sequelize不聲明名稱空間。

我只想在我的命名空間中導入一些通用類型。

我使用打字稿版本2.0.3。

在文件中使用import語句時,TypeScript會將其視為模塊。 因此,您在其中聲明的任何名稱空間將不再是全局的,而是在該模塊本地的。

導入您的接口,然后將名稱空間聲明包裝在一個declare global { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM