【问题标题】:TS2339: Property does not exist on typeTS2339:类型上不存在属性
【发布时间】:2017-02-25 09:35:18
【问题描述】:

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

我有以下 sn-p:

///<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:“全局”类型上不存在属性“base_dir”

TS2339:“全局”类型上不存在属性“abs_path”

TS2339:“全局”类型上不存在属性“包含”

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

///<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";

所以现在整个 sn-p 是这样的:

///<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:“全局”类型上不存在属性“base_dir”

TS2339:“全局”类型上不存在属性“abs_path”

TS2339:“全局”类型上不存在属性“包含”

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

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

任何帮助将不胜感激!

【问题讨论】:

  • @lena 谢谢,这正是我的问题,并且在此链接中非常清楚地详细说明。您可以将其写为答案,我会将其标记为已接受的答案。一如既往地感谢你!

标签: typescript webstorm


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-03-14
    • 2021-11-24
    • 2019-01-11
    • 2021-05-08
    • 2021-10-15
    • 2020-12-13
    • 2021-08-04
    • 2020-07-01
    • 2021-06-03
    相关资源
    最近更新 更多