繁体   English   中英

Typescript Node JS - 类型“Global & typeof globalThis”上不存在“属性”

[英]Typescript Node JS - `Property does not exist on type 'Global & typeof globalThis'`

我有另一个使用 typescript 和 global.d.ts 文件构建的 NodeJS 应用程序,一切正常,但我的新应用程序在使用ts-node-dev ts-main-file.ts运行时出错

在新应用程序中,我在 src 文件夹中有 global.d.ts 文件,但无法识别。

global.d.ts 文件内容

declare namespace NodeJS {
  export interface Global {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    sequelize: any;
  }
}

tsconfig.json 文件内容

{
  "extends": "@tsconfig/node14/tsconfig.json",

  "compilerOptions": {
    "resolveJsonModule": true,
    "preserveConstEnums": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "outDir": "out/build",
    "types": ["reflect-metadata"]
  },
  "include": ["src/**/*", "tests/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

我不知道为什么它不起作用,但如果有人可以指出缺失的部分,那将会更有帮助。

环境详细信息:Node JS 15 ts-node-dev ver。 1.1.1(使用 ts-node 版本 9.1.1、typescript 版本 4.1.3)Linux(Pop OS 20.10)

我看到错误的文件代码片段:

async connectWithDB() {
    const databaseName = 'local_server';
    const userName = 'test';
    const password = 'Test123$';
    const host = 'localhost';
    const dialect = 'postgres';

    global.sequelize = new Sequelize(databaseName, userName, password, {
      host: host,
      dialect: dialect,
      pool: {
        max: 50,
        min: 0,
        acquire: 30000,
        idle: 10000,
      },
      define: {
        charset: 'utf8',
      },
    });

    try {
      await global.sequelize.authenticate();
      console.log('Connection has been established successfully.');
    } catch (error) {
      console.error('Unable to connect to the database:', error);

      process.exit(1);
    }
  }

使用global this或向其添加属性可能会在以后导致问题。 connectWithDB也会对 Nodejs 的global链产生副作用。 它还会创建相同 object 的多个实例。 因此,如果authentication成功,只需返回Sequelize实例,否则抛出错误并结束进程

async connectWithDB() {
    const databaseName = 'local_server';
    const userName = 'test';
    const password = 'Test123$';
    const host = 'localhost';
    const dialect = 'postgres';

    const sequelize = new Sequelize(databaseName, userName, password, {
      host: host,
      dialect: dialect,
      pool: {
        max: 50,
        min: 0,
        acquire: 30000,
        idle: 10000,
      },
      define: {
        charset: 'utf8',
      },
    });

    try {
      await sequelize.authenticate();
      console.log('Connection has been established successfully.');
      return sequelize; //return the instance if you wanna use it elsewhere..
    } catch (error) {
      console.error('Unable to connect to the database:', error);

      process.exit(1);
    }
  }

在项目层次结构的顶级文件中..如果您使用的是 express

//main.ts / server.ts etc...
import express, {Request, Response} from 'express';
const app = express();
app.set(...);
.....
.....
export const dbConnect = connectWithDB();

app.get("/route", async (req:Request, res: Response)=>{
  dbConnection.then((db)=>{
    // do whatever
   }
  )
})

或将其添加到快递请求 object..

app.use((req:Request, _, done)=>{
  dbConnection.then((db)=>{
    req.db=dbConnection;
     done();
   }
});

现在它将作为req.db对所有路由可用

尝试使用这个。

declare global {
  var sequelize: any;

}

代替

declare namespace NodeJS {
  export interface Global {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    sequelize: any;
  }
}
declare global {
   function signin(): Promise<string[]>;
   sequelize: any
}
global.signin = () => {};
global.sequelize = anything;

这有望奏效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM