0
0
Typescriptprogramming~15 mins

What survives compilation to JavaScript in Typescript - Deep Dive

Choose your learning style9 modes available
Overview - What survives compilation to JavaScript
What is it?
When TypeScript code is turned into JavaScript, some parts stay in the final JavaScript code, and some parts disappear. TypeScript adds extra features like types and interfaces that help developers write better code but are not needed when the program runs. The process of turning TypeScript into JavaScript is called compilation. This topic explains which parts of TypeScript code remain after compilation and which parts are removed.
Why it matters
Knowing what survives compilation helps you understand what your final JavaScript code looks like and how it behaves in the browser or server. It also helps you write TypeScript code that works well with JavaScript tools and libraries. Without this knowledge, you might expect some TypeScript features to exist at runtime, causing confusion and bugs.
Where it fits
Before this, you should know basic TypeScript syntax and JavaScript fundamentals. After this, you can learn about advanced TypeScript features like decorators, namespaces, and how to configure the compiler for different outputs.
Mental Model
Core Idea
Only JavaScript-compatible code remains after TypeScript compilation; all type-only information is removed.
Think of it like...
It's like writing a recipe with notes in a different language that only the chef understands; when sharing the recipe, you remove the notes and keep only the cooking steps everyone can follow.
TypeScript Source Code
┌─────────────────────────────┐
│ Code + Types + Interfaces   │
│ + Enums + Decorators        │
└─────────────┬───────────────┘
              │ Compilation
              ▼
JavaScript Output Code
┌─────────────────────────────┐
│ JavaScript code only         │
│ (no types, no interfaces)   │
│ Enums become JS objects      │
│ Classes become JS classes    │
│ Functions remain             │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationTypeScript adds types to JavaScript
🤔
Concept: TypeScript introduces types and interfaces to JavaScript to help catch errors before running code.
TypeScript lets you write variable types, function parameter types, and interfaces to describe shapes of objects. For example, you can say a variable is a number or a string. These types help the editor and compiler but do not exist in JavaScript itself.
Result
You get safer code with fewer mistakes before running your program.
Understanding that types are only for development helps you see why they don't appear in the final JavaScript.
2
FoundationCompilation removes type-only parts
🤔
Concept: When TypeScript compiles, it removes all type annotations and interfaces because JavaScript does not support them.
For example, this TypeScript code: let age: number = 30; compiles to JavaScript as: let age = 30; The ': number' part is removed because JavaScript doesn't use it.
Result
The JavaScript code runs without any type information.
Knowing that types vanish after compilation prevents confusion about runtime behavior.
3
IntermediateClasses and functions survive compilation
🤔
Concept: Classes and functions in TypeScript become JavaScript classes and functions after compilation.
TypeScript classes with methods and constructors compile to JavaScript classes or function prototypes depending on the target version. Functions remain as normal JavaScript functions. For example: class Person { name: string; constructor(name: string) { this.name = name; } greet() { return `Hello, ${this.name}`; } } compiles to JavaScript with the class and methods intact, but without type annotations.
Result
You get JavaScript classes and functions that work as expected at runtime.
Recognizing that executable code stays intact helps you trust that your logic runs correctly.
4
IntermediateEnums become JavaScript objects
🤔
Concept: TypeScript enums are converted into JavaScript objects with properties representing enum members.
For example, this enum: enum Color { Red, Green, Blue } compiles to JavaScript as: var Color = { Red: 0, Green: 1, Blue: 2 }; This object can be used like an enum in JavaScript.
Result
You can use enums in JavaScript even though JavaScript has no native enum type.
Knowing enums become objects explains how TypeScript adds features missing in JavaScript.
5
IntermediateInterfaces disappear completely
🤔
Concept: Interfaces are only for type checking and do not produce any JavaScript code.
For example: interface User { name: string; age: number; } has no JavaScript output. It only helps during development to check that objects match the shape.
Result
Interfaces help you write correct code but do not affect runtime.
Understanding interfaces vanish prevents expecting runtime checks or objects.
6
AdvancedDecorators require runtime support
🤔Before reading on: do you think decorators are removed or kept after compilation? Commit to your answer.
Concept: Decorators are special functions that modify classes or methods and survive compilation if enabled, but require extra runtime support.
Decorators add code that runs when the program starts to change behavior. TypeScript compiles decorators into JavaScript calls, but you must enable experimental support and include helper code. Without this, decorators won't work at runtime.
Result
Decorators become JavaScript functions that modify classes or methods dynamically.
Knowing decorators survive but need runtime setup helps avoid confusion about their behavior.
7
ExpertType-only imports vanish in output
🤔Quick: Do type-only imports generate JavaScript import statements? Commit to yes or no.
Concept: Imports used only for types are removed from the JavaScript output to avoid unnecessary code.
For example: import type { User } from './models'; This import is erased during compilation because it only provides type information. Only imports used in executable code remain.
Result
JavaScript output contains only imports needed at runtime, reducing bundle size.
Understanding this helps optimize code and prevents runtime errors from missing imports.
Under the Hood
The TypeScript compiler parses the source code and builds a type-checking layer that verifies types and interfaces. During compilation, it strips out all type annotations, interfaces, and type-only imports because JavaScript engines do not understand them. It transforms TypeScript-specific features like enums and decorators into equivalent JavaScript code. The compiler outputs clean JavaScript that can run in any JavaScript environment.
Why designed this way?
TypeScript was designed as a superset of JavaScript to add static typing without changing runtime behavior. Removing types during compilation keeps the output compatible with all JavaScript engines. This design avoids performance overhead and complexity at runtime while providing strong developer tooling during development.
TypeScript Source
┌─────────────────────────────┐
│ Code + Types + Interfaces   │
│ + Enums + Decorators        │
└─────────────┬───────────────┘
              │ Parsing & Type Checking
              ▼
Intermediate Representation
┌─────────────────────────────┐
│ Types checked, errors found │
│ Type info marked for removal│
└─────────────┬───────────────┘
              │ Code Transformation
              ▼
JavaScript Output
┌─────────────────────────────┐
│ Executable JS code only      │
│ Enums as objects            │
│ Decorators as functions     │
│ No types or interfaces      │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do TypeScript interfaces exist at runtime in JavaScript? Commit to yes or no.
Common Belief:Interfaces are real objects in JavaScript after compilation.
Tap to reveal reality
Reality:Interfaces are completely removed during compilation and do not exist at runtime.
Why it matters:Expecting interfaces at runtime can cause confusion and bugs when trying to access them.
Quick: Do type annotations affect the performance of JavaScript code? Commit to yes or no.
Common Belief:Type annotations slow down the JavaScript program because they add extra checks.
Tap to reveal reality
Reality:Type annotations are removed before runtime, so they have no impact on performance.
Why it matters:Misunderstanding this might lead to avoiding TypeScript for fear of slower code.
Quick: Do decorators work automatically without extra setup? Commit to yes or no.
Common Belief:Decorators just work after compilation without any configuration.
Tap to reveal reality
Reality:Decorators require enabling experimental support and runtime helpers to function properly.
Why it matters:Not knowing this causes runtime errors or silent failures when using decorators.
Quick: Do type-only imports generate JavaScript import statements? Commit to yes or no.
Common Belief:All imports in TypeScript become JavaScript imports.
Tap to reveal reality
Reality:Imports used only for types are removed during compilation and do not appear in JavaScript.
Why it matters:Expecting type-only imports at runtime can cause missing module errors.
Expert Zone
1
TypeScript's removal of types means runtime type checks must be added manually if needed, which is a common source of bugs.
2
Enums compiled to objects can be reverse-mapped in JavaScript, a subtle feature that enables bidirectional lookup.
3
Decorators' runtime behavior depends heavily on the target JavaScript version and compiler options, affecting compatibility.
When NOT to use
Avoid relying on TypeScript types for runtime validation; use libraries like 'io-ts' or manual checks instead. Also, do not use decorators in environments without proper support or when targeting older JavaScript versions without transpilation.
Production Patterns
In production, developers write TypeScript for safety but deploy only JavaScript. They use build tools to strip types and optimize code. Decorators are used carefully with proper configuration. Type-only imports help reduce bundle size by removing unnecessary code.
Connections
Static Type Checking
Builds-on
Understanding what survives compilation clarifies how static type checking improves code safety without affecting runtime.
JavaScript Runtime
Opposite
Knowing that TypeScript types vanish highlights the difference between compile-time and runtime environments.
Compiler Design
Same pattern
The process of removing non-executable code during compilation is common in many languages, showing a universal compiler strategy.
Common Pitfalls
#1Expecting interfaces to exist at runtime and trying to access them.
Wrong approach:console.log(User); // User is an interface in TypeScript
Correct approach:// Interfaces do not exist at runtime, so avoid accessing them // Use runtime objects or classes instead
Root cause:Misunderstanding that interfaces are only for compile-time type checking.
#2Using decorators without enabling experimental support.
Wrong approach:@Component() class MyClass {}
Correct approach:// Enable 'experimentalDecorators' in tsconfig.json // and include necessary runtime helpers
Root cause:Not knowing decorators require compiler and runtime configuration.
#3Importing types without 'import type' and expecting no runtime import.
Wrong approach:import { User } from './models'; // Used only as a type
Correct approach:import type { User } from './models'; // Removed from JS output
Root cause:Not distinguishing between type-only and value imports.
Key Takeaways
TypeScript adds types and interfaces that help during development but are removed during compilation.
Only executable JavaScript code like classes, functions, and enums survive compilation.
Interfaces and type annotations vanish completely and do not exist at runtime.
Decorators survive compilation but require special compiler options and runtime support.
Type-only imports are erased to keep the JavaScript output clean and efficient.