1

Node is able to run the following without errors (node hello-world.ts):

var f = () => {
    console.log('Hello World!');
};

f();

However, when I try this file:

interface Accountable {
    getIncome() : number;
}

I get get the following exception:

interface Accountable {
          ^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:414:25)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

I've tried adding --target ES5 and ES2015 to the TSC settings page, but no effect.

6
  • 1
    Do you realize that node.js does not run TypeScript syntax files directly? You have to transpile it to plain JS and then run that plain JS file with node.js. Your first code example is legal ES6 code which is why node.js can run it. Commented Apr 12, 2016 at 16:31
  • I assumed it was doing so 'under the hood'. Why is one file OK, and the other not though? Both are runs directly with node filename.ts. Commented Apr 12, 2016 at 16:33
  • 1
    node.js has no "under the hood" transpile capabilities. You have to do that yourself before giving the file to node.js. Your first code example works because it's legal ES6 Javascript. node.js has no built-in TypeScript support. Commented Apr 12, 2016 at 16:34
  • That would explain it then. Commented Apr 12, 2016 at 16:35
  • If you'd like to directly run .ts files from the command line without transpiling, you can use ts-node Commented Apr 12, 2016 at 18:08

2 Answers 2

2

Making my comments into an answer.

Node.js has no built-in support for TypeScript and no built-in support for automatically transpiling TypeScript into plain JavaScript. As such, you have to transpile your TypeScript files first before running them in node.js.

Your first code example works because it is legal ES6 JavaScript syntax and thus node.js can just run it directly.

Sign up to request clarification or add additional context in comments.

Comments

0

I've had the same problem using both VS Code and WebStorm. Thanks to cdbjorin I was able to make it work by changing one line in the Package.json file:

...
"name": "myProject",
"version": "0.0.0",
"private": true,
"scripts": {
  "start": "node ./myScript.ts"// <--
},
...

to:

"start": "ts-node ./myscript.ts"

Or in this case simply use ts-node myScript.ts to run it;

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.