N
N
netW0rm2016-03-09 17:42:34
JavaScript
netW0rm, 2016-03-09 17:42:34

How to disable global type definition for variables in typescript?

I read TypeScript Deep Dive and found out that the variables declared in each project file are globally defined for typescript.
For example:

// foo.ts
const foo = 'foo'

// bar.ts Другой файл проекта
const bar = foo

Will compile without errors typescript sees that foo is defined in another file. For browser scripts, this behavior may be logical, but in nodejs it can be a problem. For example, when running the compiled bar.ts node says ReferenceError: foo is not defined. Interested in the question of how to get rid of this behavior by default?
For example, the book suggests using namespace, which is of course logical if we are writing a script that will be executed in the browser. In nodejs, each file has its own execution context and is a separate module on its own, it is inconvenient and unnecessary to use namespace in each file.
If we export something using export, then typescript will not make the type separation in this file into the global scope. Then you can write something like this at the beginning of the file
export const __ = null
const foo = 'foo'

Now foo is not defined in other files.
But firstly, it's a hack, secondly, it's inconvenient, and thirdly, you can forget
. Most of all, I'm worried about another question. I tried to find the answer in the documentation, googled, and found nothing. It turns out for others this is not a problem, so I don’t understand something? Ask for help from the community

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question