Home > Software design >  TypeScript Global Scope
TypeScript Global Scope

Time:10-10

I am a beginner to TypeScript. I read online that functions have a global scope by default in TypeScript.

So I have:

const addTwo = (num) => {return (num   2)};

in file1.ts and:

console.log(addTwo(4));

in file2.ts.

Then I transpile using tsc file1.ts file2.ts which works, but then when I try to run them using node talk1.js talk2.js nothing prints out. Why does this happen and how do I fix it? Thanks!

CodePudding user response:

If you want to use the global scope like this you need to execute both files in the same context. In the browser you could do that just by adding two <script> tags, in Node however, you would need to combine the files.

It is not recommended to do this because...

  • You need to keep track of the correct order in which files are added
  • You can easily get name conflicts because all top-level names share the same scope
  • There is no built-in support for executing files like this in Node

I would recommend reading about the different module systems (Node originally only used CommonJS but now also supports ES modules) and using one of those. TypeScript has a module option for outputting the various module formats.

CodePudding user response:

what global scope means is global scope in the current file

If you want to use addTwo function from file1.ts in file2.ts you should first export it:

// file1.ts
export const addTwo = (num) => {return (num   2)};

then import it in file2.ts

// file2.ts
import { addTwo } from './polyfills';

console.log(addTwo(4));

then compile file2.ts and run it

tsc file2.ts
node file2.js

Read more about ts modules

  • Related