Bird
Raised Fist0
Typescriptprogramming~15 mins

What types exist only at compile time in Typescript - Deep Dive

Choose your learning style10 modes available
Overview - What types exist only at compile time
What is it?
In TypeScript, some types exist only during the process of checking your code before it runs. These types help catch mistakes early but disappear when the program is turned into JavaScript to run. They do not create any code or data that runs in the browser or server. These are called compile-time-only types.
Why it matters
Without compile-time-only types, developers would have to find errors by running the program, which can be slow and error-prone. These types help catch bugs early, making code safer and easier to maintain. Without them, programs would be more likely to crash or behave unexpectedly in real use.
Where it fits
Before learning about compile-time-only types, you should understand basic TypeScript types and how TypeScript compiles to JavaScript. After this, you can learn about advanced type features like conditional types, mapped types, and type inference that build on compile-time-only types.
Mental Model
Core Idea
Compile-time-only types exist to check your code before it runs but vanish completely when the program runs.
Think of it like...
It's like a teacher grading your homework with red pen marks that disappear after you submit the final copy; the marks help you fix mistakes but don't appear in the final version.
TypeScript Code
  ├─ Compile-time Types (check errors, no runtime code)
  └─ Runtime JavaScript (runs in browser/server, no types)

[Compile-time Types] --(disappear)--> [Runtime JavaScript]
Build-Up - 7 Steps
1
FoundationUnderstanding TypeScript Types
🤔
Concept: TypeScript uses types to describe the shape and kind of data in your code.
Types like string, number, and boolean tell TypeScript what kind of values variables can hold. This helps catch mistakes like adding a number to a string incorrectly.
Result
You get errors during coding if you use values in the wrong way, before running the program.
Knowing that types describe data helps you see why TypeScript can catch errors early.
2
FoundationCompile Time vs Runtime Explained
🤔
Concept: TypeScript checks types before running code, but the types do not exist when the code runs.
TypeScript code is turned into JavaScript by removing all type information. The JavaScript runs in browsers or servers without any types.
Result
Your program runs without any type checks at runtime, so type errors must be caught before running.
Understanding this separation explains why some types only exist during compilation.
3
IntermediateTypes That Vanish After Compilation
🤔Before reading on: do you think interfaces exist in the final JavaScript code or only during compile time? Commit to your answer.
Concept: Interfaces and type aliases are examples of types that exist only at compile time and do not produce JavaScript code.
Interfaces describe object shapes but disappear after compilation. Type aliases give names to types but also vanish. They help TypeScript check your code but do not create any runtime code.
Result
No JavaScript code is generated for interfaces or type aliases, so they cannot affect runtime behavior.
Knowing which types vanish helps you write clean code without worrying about runtime overhead.
4
IntermediateLiteral Types and Union Types
🤔Before reading on: do you think literal types like 'hello' or union types like 'string | number' exist at runtime? Commit to your answer.
Concept: Literal types and union types are compile-time constructs that help narrow down possible values but do not exist in the final JavaScript.
Literal types let you specify exact values like 'hello'. Union types allow variables to be one of several types. Both are used only during type checking and removed when compiling.
Result
These types help catch errors like passing wrong values but do not add any code to the output.
Understanding these types' compile-time-only nature prevents confusion about runtime behavior.
5
IntermediateConditional and Mapped Types
🤔Before reading on: do you think conditional types create new JavaScript functions or objects at runtime? Commit to your answer.
Concept: Conditional and mapped types are advanced compile-time types that create new types based on conditions or transformations but do not exist at runtime.
Conditional types choose one type or another based on a condition. Mapped types create new types by transforming properties. Both are powerful tools for type safety but vanish after compilation.
Result
They enable complex type logic without affecting runtime code size or speed.
Knowing these types only exist at compile time helps you use them confidently without runtime cost.
6
AdvancedEnums: Compile Time vs Runtime
🤔Before reading on: do you think all enums disappear after compilation or some remain in JavaScript? Commit to your answer.
Concept: TypeScript has two kinds of enums: const enums that vanish at compile time, and regular enums that generate JavaScript code.
Const enums are replaced with their values during compilation and do not exist at runtime. Regular enums create JavaScript objects to represent the enum, so they exist at runtime.
Result
Choosing the right enum type affects whether enum data exists in the final program or not.
Understanding this difference helps optimize code size and behavior.
7
ExpertType Erasure and Its Implications
🤔Before reading on: do you think TypeScript's type system affects runtime performance or memory usage? Commit to your answer.
Concept: TypeScript uses type erasure, meaning all types are removed during compilation, so they have no runtime cost or presence.
Because types vanish, TypeScript cannot enforce types at runtime. This means runtime errors can still happen if JavaScript code misbehaves. Developers must rely on compile-time checks and tests.
Result
TypeScript improves developer experience but does not guarantee runtime safety by itself.
Knowing type erasure clarifies the limits of TypeScript's safety and the need for runtime checks or tests.
Under the Hood
TypeScript's compiler analyzes the source code and uses types to check correctness. During compilation, it removes all type annotations, interfaces, type aliases, and other compile-time-only constructs. The output is plain JavaScript with no type information. This process is called type erasure.
Why designed this way?
TypeScript was designed to add types to JavaScript without changing its runtime behavior or performance. Removing types at compile time ensures compatibility with all JavaScript environments and avoids runtime overhead. Alternatives like runtime type checking were rejected to keep JavaScript fast and simple.
Source TypeScript Code
  │
  ├─ Type Checking (compile time only)
  │
  └─ Type Erasure (remove types)
       ↓
  Output JavaScript Code (no types, runs in browser/server)
Myth Busters - 4 Common Misconceptions
Quick: Do interfaces exist in the JavaScript output? Commit yes or no before reading on.
Common Belief:Interfaces create JavaScript objects that exist at runtime.
Tap to reveal reality
Reality:Interfaces are removed completely during compilation and do not produce any JavaScript code.
Why it matters:Thinking interfaces exist at runtime can lead to confusion about how to use them and why they don't affect program behavior.
Quick: Do literal types like 'hello' create string constants in JavaScript? Commit yes or no before reading on.
Common Belief:Literal types create actual string values in the output code.
Tap to reveal reality
Reality:Literal types only exist during type checking and do not create any runtime values.
Why it matters:Believing literal types exist at runtime can cause misunderstandings about code size and behavior.
Quick: Do all enums vanish after compilation? Commit yes or no before reading on.
Common Belief:All enums disappear after compilation like other types.
Tap to reveal reality
Reality:Only const enums vanish; regular enums generate JavaScript code and exist at runtime.
Why it matters:Misunderstanding this can cause bugs or unexpected code size increases.
Quick: Does TypeScript's type system prevent all runtime errors? Commit yes or no before reading on.
Common Belief:TypeScript types guarantee no runtime errors related to types.
Tap to reveal reality
Reality:TypeScript types only check code at compile time; runtime errors can still happen if JavaScript code misbehaves.
Why it matters:Overestimating TypeScript's safety can lead to missing necessary runtime checks or tests.
Expert Zone
1
Some advanced types like conditional and mapped types can create very complex compile-time logic that does not translate to runtime, which can confuse debugging if not understood.
2
Const enums improve performance by removing enum objects but can cause issues with debugging or when consuming compiled code from other modules.
3
TypeScript's type erasure means that generic types do not exist at runtime, so techniques like reflection or runtime type checks require extra code or libraries.
When NOT to use
Compile-time-only types are not suitable when you need runtime type information or validation. In those cases, use runtime type checking libraries like io-ts or zod that generate code to check types during execution.
Production Patterns
In production, developers use compile-time-only types to ensure code correctness and maintainability. They combine this with runtime validation for external data. Const enums are used to reduce code size, while regular enums are used when runtime enum objects are needed.
Connections
Static Type Checking
Builds-on
Understanding compile-time-only types deepens your grasp of static type checking, which verifies code correctness before running.
Runtime Type Validation
Opposite
Knowing that compile-time types vanish clarifies why runtime validation is necessary for data from outside sources.
Compiler Design
Same pattern
Compile-time-only types illustrate the compiler design principle of type erasure, where information used for checking is removed before execution.
Common Pitfalls
#1Expecting interfaces to exist at runtime for type checks.
Wrong approach:if (myVar instanceof MyInterface) { /* ... */ }
Correct approach:Use user-defined type guards or runtime checks instead, e.g., function isMyInterface(obj: any): obj is MyInterface { return typeof obj.prop === 'string'; }
Root cause:Misunderstanding that interfaces are erased and do not produce runtime code.
#2Using regular enums when const enums would be better for performance.
Wrong approach:enum Colors { Red, Green, Blue } // generates JS object
Correct approach:const enum Colors { Red, Green, Blue } // replaced with values at compile time
Root cause:Not knowing the difference between const and regular enums and their runtime impact.
#3Assuming TypeScript prevents all runtime type errors.
Wrong approach:const user: User = JSON.parse(input); // no runtime check
Correct approach:Use runtime validation libraries to check input before assigning to typed variables.
Root cause:Believing compile-time types enforce runtime safety without extra checks.
Key Takeaways
Compile-time-only types in TypeScript help catch errors before running code but do not exist in the final JavaScript output.
Interfaces, type aliases, literal types, union types, conditional types, and mapped types are examples of types that vanish after compilation.
Enums can be either compile-time-only (const enums) or runtime objects (regular enums), affecting code size and behavior.
TypeScript uses type erasure to keep runtime code clean and fast, but this means runtime type safety is not guaranteed.
Understanding what types exist only at compile time helps write better TypeScript code and know when runtime checks are needed.

Practice

(1/5)
1. Which of the following TypeScript types exist only at compile time and do not produce any JavaScript code?
easy
A. Functions and variables
B. Classes and enums
C. Interfaces and type aliases
D. Objects and arrays

Solution

  1. Step 1: Understand TypeScript compile-time types

    Interfaces and type aliases are used only to check types during compilation and do not exist in the final JavaScript.
  2. Step 2: Identify runtime constructs

    Classes, enums, functions, variables, objects, and arrays exist in the JavaScript output and run at runtime.
  3. Final Answer:

    Interfaces and type aliases -> Option C
  4. Quick Check:

    Compile-time only types = Interfaces, type aliases [OK]
Hint: Remember: interfaces and types vanish after compiling [OK]
Common Mistakes:
  • Thinking classes are compile-time only
  • Confusing enums with type aliases
  • Assuming variables are compile-time types
2. Which syntax correctly declares a type alias that exists only at compile time in TypeScript?
easy
A. type User = { name: string; age: number };
B. const User = { name: 'Alice', age: 30 };
C. class User { name: string; age: number; }
D. enum User { Name, Age }

Solution

  1. Step 1: Identify type alias syntax

    Using type User = { ... } declares a type alias that exists only during compilation.
  2. Step 2: Differentiate from runtime declarations

    Const objects, classes, and enums produce JavaScript code and exist at runtime.
  3. Final Answer:

    type User = { name: string; age: number }; -> Option A
  4. Quick Check:

    Type alias syntax = type ... = ... [OK]
Hint: Type aliases start with 'type' keyword [OK]
Common Mistakes:
  • Using const or class instead of type alias
  • Confusing enums with types
  • Missing semicolon in type alias
3. What will be the output of the following TypeScript code when compiled and run in JavaScript?
interface Person { name: string; age: number; }
const p: Person = { name: 'Bob', age: 25 };
console.log(typeof Person);
medium
A. "undefined"
B. "object"
C. "function"
D. "string"

Solution

  1. Step 1: Understand interface removal at compile time

    Interfaces do not exist in JavaScript output, so Person is not defined at runtime.
  2. Step 2: Evaluate typeof on undefined identifier

    Using typeof Person when Person is not defined returns "undefined" as a string.
  3. Final Answer:

    "undefined" -> Option A
  4. Quick Check:

    Interfaces vanish, typeof interface = "undefined" [OK]
Hint: Interfaces disappear; typeof interface is undefined [OK]
Common Mistakes:
  • Expecting 'object' because of interface
  • Thinking interface is a function
  • Confusing interface with class
4. Identify the error in this TypeScript code snippet:
type Animal = { species: string };
console.log(Animal);
medium
A. Missing semicolon after type declaration
B. Animal should be declared as an interface
C. Type alias syntax is incorrect
D. Animal is not defined at runtime, so console.log causes an error

Solution

  1. Step 1: Recognize type alias compile-time only nature

    Type aliases do not exist in JavaScript, so Animal is not a runtime value.
  2. Step 2: Understand console.log usage

    Trying to log Animal causes a runtime error because it is undefined in JavaScript.
  3. Final Answer:

    Animal is not defined at runtime, so console.log causes an error -> Option D
  4. Quick Check:

    Logging type alias = runtime error [OK]
Hint: Type aliases can't be used as runtime values [OK]
Common Mistakes:
  • Thinking type aliases exist at runtime
  • Ignoring runtime vs compile-time difference
  • Assuming missing semicolon causes error
5. You want to create a function that accepts only objects matching a specific shape but does not add any runtime overhead. Which TypeScript feature should you use?
hard
A. Use a type alias and create a runtime object
B. Use an interface to define the object shape
C. Use a class to define the object shape
D. Use an enum to define the object shape

Solution

  1. Step 1: Understand compile-time type checking

    Interfaces define object shapes only at compile time and do not generate JavaScript code, so no runtime overhead.
  2. Step 2: Compare with other options

    Classes and enums generate runtime code; type aliases do not create runtime objects unless explicitly instantiated.
  3. Final Answer:

    Use an interface to define the object shape -> Option B
  4. Quick Check:

    Interfaces = compile-time only, no runtime overhead [OK]
Hint: Interfaces check shape without runtime cost [OK]
Common Mistakes:
  • Using classes which add runtime code
  • Confusing enums with object shapes
  • Thinking type aliases create runtime objects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard