打字稿:类型'Global'不存在属性'DB'

时间:2019-09-22 11:41:21

标签: javascript typescript

在我的src/app.ts中,我有:

import DB from '../models'

src/models/index.ts中,我有:

export default (() => {
    if (global.DB) {
        return global.DB
    }
    ...
    // Do some other stuff
    return something

我的typings/global.d.ts有:

declare namespace NodeJS {
    export interface Global {
        DB: any;
    }
}

declare var DB: any;

最后,我的tsconfig.json拥有:

{
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es6",
        "esModuleInterop": true,
        "sourceMap": true
    },
    "include": [
        "./src/**/*"
    ],
    "files": [
        "typings/*"
    ]
}

但是我仍然收到错误:

Error: src/models/index.ts(7,16): error TS2339: Property 'DB' does not exist on type 'Global'.

我做错了什么?

1 个答案:

答案 0 :(得分:8)

您的tsconfig.json可能是错误的。您同时使用filesinclude来指定glob。 files应该用于specific (relative or absolute) paths,而include可以用于glob。

如果您将两条路径合并到include中,如下所示:

{
  "compilerOptions": {
      "outDir": "./built",
      "allowJs": true,
      "target": "es6",
      "esModuleInterop": true,
      "sourceMap": true,
  },
  "include": [
      "./src/**/*",
      "./typings/*"
  ]
}

您的文件应编译。