Why does TS code need to be compiled?
1. Because browsers and Node.js do not understand TypeScript
TypeScript is a superset of JavaScript, and its main purpose is adding types and new syntax features. But:
- browsers and Node.js execute only JavaScript,
- so TypeScript cannot be run directly.
Example:
javascript
const user: string = "Tim";The browser does not know what
: stringis and throws an error if you try to run this code directly.
2. What the compiler (tsc) does
The TypeScript compiler (tsc) performs two steps:
- Type checking It analyzes the whole project and checks whether the values match the declared types.
javascript
let count: number = "5"; // Error: number expected- Transpilation (conversion)
It removes all type information (
: string,interface,type,enum, etc.) and generates plain JavaScript that can be run.
javascript
// After compilation:
var user = "Tim";3. Example: before and after compilation
TypeScript (developer's code)
javascript
function greet(name: string): string {
return `Hello, ${name}!`;
}After compiling to JS
javascript
function greet(name) {
return "Hello, " + name + "!";
}The types (
: string) disappear completely - only plain JavaScript is left.
4. Compilation also lets you:
- Use modern JS features (ES2022, ESNext) even in old browsers
tscconverts the code to an older standard (for example, ES5);- Check type compatibility across files;
- Configure the build for different environments (
target,module,outDir); - Work with modules, namespaces, decorators, and enums, which JS does not have.
5. What exactly happens during a build
If you have a project with a tsconfig.json, running:
javascript
npx tscTypeScript:
- Checks all
.tsand.tsxfiles; - Catches type errors;
- Generates
.jsfiles into the specified directory (outDir); - (optionally) Creates
.d.tsfiles - type descriptions for libraries.
6. Summary
TypeScript needs to be compiled because:
- it is not an executable language (browsers do not understand TS);
- it contains type information that needs to be removed;
- it often uses new syntax that requires conversion to compatible JavaScript.
Compilation makes the code safe, checked, and compatible with any JS environment.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.