首页 > 解决方案 > Typescript Node JS - `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,打字稿版本 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);
    }
  }

标签: node.jstypescript

解决方案


尝试使用这个。

declare global {
  var sequelize: any;

}

代替

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

推荐阅读