Compiling TypeScript to JavaScript
Learn Compiling TypeScript to JavaScript
Compilation transforms TypeScript source into JavaScript suitable for the chosen target environment.
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 compiling typescript to javascript.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
The tsc command accepts source paths and compiler options. --target controls which JavaScript syntax is emitted; --module controls module output. Strict checking catches more unsafe assumptions. Use --noEmit to check only, and --noEmitOnError when emission must stop on diagnostics.
Example terminal command: npx tsc --strict --target es2022 --module commonjs hello.ts.
See the concept visually
Use the diagram to locate the checks, values or branches involved in the example.
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
function welcome(name: string): string {
return `Welcome, ${name}`;
}
console.log(welcome("Asha"));Verified output
Welcome, AshaHow 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 parameter and return annotations are part of static checking. In the emitted JavaScript the welcome function still builds the same template string and receives "Asha".
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
Compiling is not the same as bundling: tsc does not automatically package every dependency into one browser-ready file.
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
Use npx tsc --strict --target es2022 --module commonjs hello.ts; inspect hello.js and locate which parts of the source were erased.
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
Compiling TypeScript to JavaScript: The tsc command accepts source paths and compiler options.
--noEmit runs the type checker without producing output files.
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.