Protected: Typescript wrongly assumes browser context

in Front-End Web Technologies

Running Typescript under NodeJS is easy

Create a new main.ts file and put some code inside it

console.log("Hello Typescript under NodeJS");

Install typescript compiler using

npm install typescript

Compile your code (I am assuming Windows file path style)

node_modules\.bin\tsc

And just execute it using NodeJS

node main.js

You should be aware that Typescript assumes your code is executed under a browser and therefore let you use browser specific API. For example, the following code compiles successfully but fails to execute under NodeJS

localStorage.setItem("key", "123");

Fortunately, we can fix that

Add a tsconfig.json file and let Typescript know the appropriate execution context


 {
    "compilerOptions": {
      "module": "commonjs",
      "target": "es5",
      "sourceMap": true,
      "lib": ["ES6"]
    },
    "exclude": [
      "node_modules"
   ]
 }

The lib section tells Typescript what external libraries it should support out of the box. In this case we just want to be able to compile some ES6 APIs

With the new configuration the Typescript compiler now generates the following error

Cannot find name ‘localStorage’

Which is exactly what we want

However, running with above configuration also fails to compile to following valid NodeJS code


console.log("Hello Typescript under NodeJS");

Typescript throws the following error

Cannot find name ‘console’

To fix that you need to install NodeJS typings information using the following command

npm install @types/node

Enjoy, …

Contact us
You might also like
Share: