Note: Actually asked in stackoverflow, but can't get an answer. Not sure if feature (i.e. my lack of understanding) or bug.
The following is a minimal reproduction of the error:
file.ts:
/// <reference path="types.d.ts" />
var directory: Path = "test";
I would like to reference the type Path in another file types.d.ts..
types.d.ts:
/// <reference path="node.d.ts"/>
import fs = require("fs"); //Adding this line causes the problem
declare type Path = string;
declare interface FileStructure {
filename: Path;
hash?: string;
stat?: fs.Stats; //but i need it for this.
}
The issue is that adding the line import fs = require("fs") (even without declaring the other interface) causes the following errors:
file.ts(2,18): error TS2304: Cannot find name 'Path'
types.d.ts(2,1): error TS1148: Cannot compile modules unless the '--module' flag is provided.
Declaring either --module commonjs or --module amd still leaves the first error: TS2304: Cannot find name 'Path'.
Note: typescript 1.6.2
A file is considered as a module if it has a top-level import or export. modules have their own scope, and have to be consumed through importing them. they also assume the existence of a module loader at run time; the --module flag tells the compiler which module loader you are using, e.g. commonJS if you are using node, amd if you are using require js or something compatible, system if you are using es6-module-loader and System Js.. etc..
I am guessing you are using CommonJS, just as you are importing "fs".
For you to be able to access the type Path you need to first export Path, and second import module types. some this should work:
// types.d.ts
/// <reference path="node.d.ts"/>
import fs = require("fs"); //Adding this line causes the problem
export type Path = string;
export interface FileStructure {
filename: Path;
hash?: string;
stat?: fs.Stats; //but i need it for this.
}
// file.ts
import {Path} from "types";
var directory: Path = "test";
then invoke the compiler as:
tsc --m commonjs file.ts types.d.ts
you can find more documentation about using modules at: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Modules.md
Thanks very much for your help :)
Most helpful comment
A file is considered as a module if it has a top-level
importorexport. modules have their own scope, and have to be consumed through importing them. they also assume the existence of a module loader at run time; the--moduleflag tells the compiler which module loader you are using, e.g.commonJSif you are using node,amdif you are using require js or something compatible,systemif you are using es6-module-loader and System Js.. etc..I am guessing you are using CommonJS, just as you are importing "fs".
For you to be able to access the type
Pathyou need to first exportPath, and second import moduletypes. some this should work:then invoke the compiler as:
you can find more documentation about using modules at: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Modules.md