typescript - TS2339 : Property does not exist on type

标签 typescript webstorm

我在 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'

所以我将它们添加到“全局”界面,如下所示:

///<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 语句

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

任何帮助将不胜感激!

最佳答案

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

关于typescript - TS2339 : Property does not exist on type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068806/

相关文章:

typescript - 如何将 typescript 定义文件添加到 npm 包中?

reactjs - 如何在 React Native 中将 ref 从父级传递给子级 Touchable Opacity?

javascript - Observable.create(...).map 不是函数

javascript - 在 typescript 中导入 JSON 时如何禁用/断言/覆盖推断类型

emacs - 删除 Webstorm 右侧的一个字符

meteor - WebStorm 和 Meteor 的迟钝?

angular - 你如何使用 Observable.bindCallback()

angular - 禁止在 Nrwl Nx 中的同一库中导入桶文件

intellij-idea - Intellij - 不应编辑生成的源代码(即使它没有生成)

intellij-idea - IntelliJ IDEA中ES6模板文字(反引号)的文本突出显示