What survives compilation to JavaScript in Typescript - Time & Space Complexity
When TypeScript code is turned into JavaScript, some parts stay and some parts disappear.
We want to know which parts keep running and affect how long the program takes.
Analyze the time complexity of the following TypeScript code after compilation.
interface User {
id: number;
name: string;
}
function greet(user: User) {
console.log(`Hello, ${user.name}`);
}
const user = { id: 1, name: "Alice" };
greet(user);
This code defines a type, a function using that type, and calls the function.
Look for loops or repeated steps that run many times.
- Primary operation: The function call and console output.
- How many times: Called once here, but could be many times if used in a loop.
Since the type information disappears, only the function and its calls affect time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls and prints |
| 100 | 100 function calls and prints |
| 1000 | 1000 function calls and prints |
Pattern observation: The work grows directly with how many times the function runs, not with type checks.
Time Complexity: O(n)
This means the program's running time depends on how many times the function is called, not on the TypeScript types.
[X] Wrong: "TypeScript types slow down the program because they add extra work at runtime."
[OK] Correct: TypeScript types are removed during compilation and do not exist in the JavaScript that runs, so they do not affect runtime speed.
Knowing what stays after compilation helps you understand what really affects your program's speed and what is just for helping you write better code.
"What if we added a loop inside the function that runs n times? How would the time complexity change?"