0

File A:var x: number = 5;

File B:var x = function (): number { return 5; };

Error:Subsqeuent variable declarations must have same type.

Removing all references (///<reference path='/Scripts/example.ts' />) has NO effect on my project. Everything still compiles, Intellisense still works. To my understanding, this is definitely not intended behavior. Any variable declared in any file is available in all files, like the one that caused the error above. I've been aware something weird was going on but I'm about to embark on a project where File B is going to have lots of variables of the same name as A, but they must remain separate. So this is an issue. But I can't find any reading on what's going on here. Everyone says you control Intellisense with the reference directive and you must use it.

Can't find anything about this in Project Settings>TypeScript, nor Tools>Options.

Licht
  • 1,079
  • 1
  • 12
  • 27
  • JavaScript isn't scoped by file. A variable declared outside any function is a global variable. – David Sherret Feb 18 '15 at 14:56
  • However it is stored in another file. Therefore shouldn't I require or declare in order for Intellisense to pick it up? – Licht Feb 18 '15 at 16:39
  • This doesn't have much to do with the reference tags because those don't have any affect on the outputted javascript. The reason why this is giving an error in TypeScript is because you are essentially doing: `window.x = 5;` and then `window.x = function() { return 5; };`. So you're re-declaring `window.x` to a different type. If you want to fix this, you can keep everything contained in `modules` or `classes` (recommended)... or you could use an [IFFE](http://stackoverflow.com/a/8228308/188246) – David Sherret Feb 18 '15 at 16:50
  • Use modules : https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1 – basarat Feb 18 '15 at 22:22

1 Answers1

2

It's expected behavior. Use modules to separate variables in different files

// file 1
module First {
    var x = 3;
}


// file 2
module Second {
    var x = function (): number { return 5; };
}

See also TypeScript module documentation and javascript module pattern

Another option would be using AMD or CommonJS compilation option of the TypeScript, see this article

Max Brodin
  • 3,903
  • 1
  • 14
  • 23