2
votes

I'm converting a js file to ts in WebStorm 2016.2.2.

I had the following snippet:

///<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 and include produced the errors:

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'

So I added them to 'Global' interface as following:

///<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));
};

It did eliminate those errors.

Then, I continued converting the rest of the file, I had to import both Request and Response from express, so I added the following:

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

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

So now the whole snippet is like that:

///<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));
};

Unfortunately, adding the import statement has returned the TS2339 error, so I stuck again with:

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 has nothing to to with this error specifically. I've tried to import from other modules and it produced the same error. It occurs when I have at least one import statement

Does someone know how can I fix it?

Any help will be profoundly appreciated!

1
@lena thanks, It's exactly my issue and it's detailed very clearly in this link. You can write it as an answer and I will mark it as the accepted answer. Thank you so much as always!Alon

1 Answers

5
votes

The problem is that any typescript file with top-level import or export becomes a module. See https://github.com/Microsoft/TypeScript/issues/1574