我在 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_dir
、abs_path
和 include
产生了错误:
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 中导入 Request
和 Response
,所以我添加了以下内容:
///<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/