TS2339: 属性 类型不存在

TS2339: Property does not exist on type

我在 WebStorm 2016.2.2 中将 js 文件转换为 ts。

我有以下片段:

///<reference path="./typings/globals/node/index.d.ts" />

global.base_dir = __dirname;

global.abs_path = function(path) {
    return global.base_dir + path;
};
global.include = function(file) {
    return require(global.abs_path('/' + file));
};

base_dirabs_pathinclude 产生了错误:

TS2339: Property 'base_dir' does not exist on type 'Global'

TS2339: Property 'abs_path' does not exist on type 'Global'

TS2339: Property 'include' does not exist on type 'Global'

所以我将它们添加到 'Global' 界面如下:

///<reference path="./typings/globals/node/index.d.ts" />

declare namespace NodeJS{
    interface Global {
        base_dir: string;
        abs_path: (path: string) => string;
        include: (file: string) => string;
    }
}

global.base_dir = __dirname;

global.abs_path = function(path) {
    return global.base_dir + path;
};
global.include = function(file) {
    return require(global.abs_path('/' + file));
};

它确实消除了那些错误。

然后,我继续转换文件的其余部分,我不得不从 express 中导入 RequestResponse,所以我添加了以下内容:

///<reference path="./typings/modules/express/index.d.ts" />

import {Request, Response} from "~express/lib/express";

所以现在整个片段是这样的:

///<reference path="./typings/globals/node/index.d.ts" />
///<reference path="./typings/modules/express/index.d.ts" />

import {Request, Response} from "~express/lib/express";

declare namespace NodeJS{
    interface Global {
        base_dir: string;
        abs_path: (path: string) => string;
        include: (file: string) => string;
    }
}

global.base_dir = __dirname;

global.abs_path = function(path) {
    return global.base_dir + path;
};
global.include = function(file) {
    return require(global.abs_path('/' + file));
};

不幸的是,添加 import 语句返回了 TS2339 错误,所以我再次坚持:

TS2339: Property 'base_dir' does not exist on type 'Global'

TS2339: Property 'abs_path' does not exist on type 'Global'

TS2339: Property 'include' does not exist on type 'Global'

BTW Express 与此错误无关。我试图从其他模块导入,但它产生了同样的错误。它发生在我至少有一个 import 语句

有人知道我该如何解决吗?

任何帮助将不胜感激!

问题是任何具有顶级导入或导出的打字稿文件都会成为一个模块。参见 https://github.com/Microsoft/TypeScript/issues/1574