0

So I'm a beginner learning typescript. I have some code like:

let num: number = 123;
console.log(123);

And when I use Node.js to run this file, which is saved as test.ts. I get SyntaxError: Unexpected token ':'.

As far as I understand, this is how we set the type of a variable in TS right? I'm using VSCode by the way, I have node and npm installed. I also have typescript installed. I verified by checking their versions. I can't find anything online for this problem because it's just so silly.

What am I doing wrong?

5
  • 4
    NodeJS does not run TypeScript. I don't know where you got the tutorial, but TypeScript needs to be compiled to JavaScript. There's no engine that runs TypeScript directly. The maximum that you can find are different modules or engines that compile TypeScript on-the-fly to make it feel that is running TypeScript directly (like Deno), but is still compiling it in memory. Also, as a side note: TypeScript has type inference. You can remove the :number and it will still understand that num is a number, as it infers the type from the assignment. Commented Oct 5, 2023 at 22:34
  • Strange. Actually, I assumed that if I could run node test.js then I could run node test.ts. I guess I was wrong. My mistake was that I wrote JS code in TS then ran it as .TS but node in this case was actually running JS. Thank you for the clarification Commented Oct 5, 2023 at 23:24
  • I guess someone can close this question, I don't know how to. Commented Oct 5, 2023 at 23:37
  • use the tsx package it runs all typescript in node from ES3 to ESNext/NodeNext it's the superior alternative to tsnode you simply run yarn tsx script.ts or whatever your target path is if using npm it's npx tsx <path to file> Commented Oct 6, 2023 at 2:09
  • I added my comment as an answer. Is better to not delete it just in case someone has the same problem, can find the answer here. PS: The tsx package is an example of the compilers that simulate running TypeScript on-the-fly I was talking about, yep. Commented Oct 6, 2023 at 7:56

1 Answer 1

1

NodeJS does not run TypeScript. TypeScript needs to be compiled to JavaScript. There's no engine that runs TypeScript directly. The maximum that you can find are different modules or engines that compile TypeScript on-the-fly to make it feel that is running TypeScript directly (like Deno), but is still compiling it in memory.

Side note: TypeScript has type inference. You can remove the :number and it will still understand that num is a number, as it infers the type from the assignment.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.