Running TypeScript Programs
Learn Running TypeScript Programs
A predictable local workflow uses TypeScript for checking and emission, then Node.js for running the generated JavaScript.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind running typescript programs.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
A small file can be compiled using npx tsc --strict --target es2022 --module commonjs main.ts and run with node main.js. Recent Node.js versions can run certain erasable TypeScript syntax natively, but native type stripping does not perform type checking and supports only syntax that can be erased without runtime transformation.
For the native TypeScript path and its limitations, see Node.js documentation.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
const prices: number[] = [20, 30, 50];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(`Total: ${total}`);Verified output
Total: 100How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
The array supplies three numeric values. reduce starts at 0 and accumulates 20, then 50, then 100. Node executes that JavaScript behavior.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
Do not treat successful node main.ts execution on a compatible Node release as proof of static correctness. Use the TypeScript checker too.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Run the sample by compiling to main.js and executing with node. Try changing one price to a string and examine the type diagnostic.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
Running TypeScript Programs: A small file can be compiled using npx tsc --strict --target es2022 --module commonjs main.
Type checking and runtime execution are different steps.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.