Bird
Raised Fist0
Typescriptprogramming~10 mins

Type erasure and its consequences in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type erasure and its consequences
Write TypeScript code with types
↓
Compile to JavaScript
↓
Remove all type info (Type Erasure)
↓
Run JavaScript code without types
↓
Possible runtime issues if types were wrong
TypeScript removes all type information during compilation, producing plain JavaScript that runs without types, which can cause runtime errors if types were incorrect.
Execution Sample
Typescript
function add(a: number, b: number): number {
  return a + b;
}

const result = add(5, '10' as any);
console.log(result);
This code defines a typed function but calls it with a wrong type, which TypeScript allows at compile time if using 'any' or ignoring errors, but causes a runtime issue after type erasure.
Execution Table
StepCode LineTypeScript CheckCompiled JS BehaviorRuntime Result
1function add(a: number, b: number): number { return a + b; }Types OK for definitionFunction compiled without typesFunction ready
2const result = add(5, '10');Type error: Argument of type 'string' not assignable to parameter of type 'number'No error, call proceeds5 + '10' = '510' (string concatenation)
3console.log(result);N/ALogs '510'Output: 510 (unexpected string)
💡 TypeScript type errors do not stop JS compilation; runtime behavior may differ due to type erasure.
Variable Tracker
VariableStartAfter add(5, '10')Final
aundefined55
bundefined'10''10'
resultundefined'510''510'
Key Moments - 3 Insights
Why does TypeScript allow calling add(5, '10') even though '10' is a string?
TypeScript actually reports a type error at compile time (see execution_table step 2), but if you ignore or bypass it, the compiled JavaScript runs without types, causing unexpected results.
What happens to type information after TypeScript compiles to JavaScript?
All type information is removed (type erasure), so JavaScript runs without any type checks, which can lead to runtime errors or unexpected behavior if types were incorrect.
Why does the output show '510' instead of 15?
Because JavaScript adds a number and a string by converting the number to a string and concatenating, not by numeric addition, showing a consequence of type erasure.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2. What does TypeScript report when calling add(5, '10')?
AType error: Argument of type 'string' not assignable to parameter of type 'number'
BNo error, call is valid
CRuntime error thrown
DFunction returns undefined
💡 Hint
Check the 'TypeScript Check' column at step 2 in the execution table
According to the variable tracker, what is the value of 'result' after calling add(5, '10')?
A15
Bundefined
C'510'
DError
💡 Hint
Look at the 'result' row in the variable tracker after the function call
If TypeScript did not erase types, what would happen at runtime when calling add(5, '10')?
AFunction returns 15 number
BRuntime error due to type mismatch
CFunction returns '510' string
DFunction returns undefined
💡 Hint
Think about how type erasure removes type checks before runtime
Concept Snapshot
TypeScript uses types only at compile time.
During compilation, all types are removed (type erasure).
The output is plain JavaScript without type checks.
Wrong types can cause runtime errors or unexpected results.
Always fix type errors before running code.
Full Transcript
TypeScript code includes types to help catch errors early. When TypeScript compiles code, it removes all type information, a process called type erasure. This means the resulting JavaScript code runs without any type checks. For example, a function expecting numbers can be called with a string, which TypeScript warns about but still compiles. At runtime, JavaScript adds a number and a string by concatenation, not addition, causing unexpected results. This shows that type erasure can lead to runtime issues if type errors are ignored. It's important to fix type errors during development to avoid such problems.

Practice

(1/5)
1. What does type erasure mean in TypeScript?
easy
A. TypeScript removes all type information when compiling to JavaScript.
B. TypeScript keeps all type information in the final JavaScript code.
C. TypeScript converts types into runtime checks automatically.
D. TypeScript adds extra type annotations in the JavaScript output.

Solution

  1. Step 1: Understand TypeScript compilation

    TypeScript compiles to JavaScript by removing all type annotations and interfaces.
  2. Step 2: Define type erasure meaning

    This removal of type info is called type erasure, meaning types exist only during development, not at runtime.
  3. Final Answer:

    TypeScript removes all type information when compiling to JavaScript. -> Option A
  4. Quick Check:

    Type erasure = types removed at compile time [OK]
Hint: Remember: TypeScript types vanish in JavaScript output [OK]
Common Mistakes:
  • Thinking types exist at runtime
  • Believing TypeScript adds runtime type checks
  • Confusing type erasure with type inference
2. Which of the following is the correct way to check a variable's type at runtime in TypeScript?
easy
A. Using typeof operator in JavaScript code.
B. Using TypeScript type annotations like string in if statements.
C. Using TypeScript interfaces to check types at runtime.
D. Using instanceof with TypeScript types.

Solution

  1. Step 1: Recall type erasure effect

    TypeScript types do not exist at runtime, so you cannot use them in runtime checks.
  2. Step 2: Identify runtime type check method

    JavaScript's typeof operator works at runtime to check primitive types like string or number.
  3. Final Answer:

    Using typeof operator in JavaScript code. -> Option A
  4. Quick Check:

    Runtime type check = typeof operator [OK]
Hint: Use JavaScript's typeof for runtime type checks [OK]
Common Mistakes:
  • Trying to use TypeScript types at runtime
  • Using interfaces for runtime checks
  • Confusing instanceof with TypeScript types
3. What will be the output of this TypeScript code after compilation and running in JavaScript?
function isString(value: any): boolean {
  return typeof value === 'string';
}

console.log(isString(123));
console.log(isString('hello'));
medium
A. true\ntrue
B. false\nfalse
C. false\ntrue
D. TypeError at runtime

Solution

  1. Step 1: Understand the function logic

    The function returns true if the input's JavaScript type is 'string', false otherwise.
  2. Step 2: Evaluate the calls

    For 123, typeof is 'number', so returns false. For 'hello', typeof is 'string', so returns true.
  3. Final Answer:

    false\ntrue -> Option C
  4. Quick Check:

    typeof 123 = number (false), typeof 'hello' = string (true) [OK]
Hint: Check typeof results for each input value [OK]
Common Mistakes:
  • Assuming TypeScript types affect runtime
  • Expecting true for number input
  • Confusing output order
4. Identify the error in this TypeScript code that tries to check if value is a number at runtime:
function checkNumber(value: any): boolean {
  if (value instanceof number) {
    return true;
  }
  return false;
}
medium
A. The function should use typeof value === 'number' instead.
B. The function should use value.constructor === Number.
C. The function is correct and will return true for numbers.
D. Using instanceof with a primitive type causes a runtime error.

Solution

  1. Step 1: Understand instanceof usage

    instanceof works with objects, not primitive types like number.
  2. Step 2: Identify error cause

    Using value instanceof number causes a runtime error because number is not a constructor function.
  3. Final Answer:

    Using instanceof with a primitive type causes a runtime error. -> Option D
  4. Quick Check:

    instanceof with primitives = error [OK]
Hint: Use typeof for primitives, not instanceof [OK]
Common Mistakes:
  • Using instanceof with primitive types
  • Thinking instanceof works like typeof
  • Ignoring runtime errors from wrong instanceof usage
5. Given that TypeScript types are erased at runtime, how can you safely handle different input types in a function that accepts string | number and returns their length or value doubled?
function process(input: string | number) {
  // What is the best way to handle types here?
}
hard
A. Rely on TypeScript types only and assume input is always correct at runtime.
B. Use JavaScript runtime checks like typeof to distinguish types and process accordingly.
C. Use instanceof to check if input is a string or number.
D. Convert input to string and always return its length.

Solution

  1. Step 1: Recall type erasure impact

    TypeScript types do not exist at runtime, so runtime checks must use JavaScript operators.
  2. Step 2: Choose correct runtime check

    Using typeof lets you detect if input is 'string' or 'number' and handle each case safely.
  3. Step 3: Avoid incorrect methods

    Relying only on TypeScript types or using instanceof with primitives is unsafe or incorrect.
  4. Final Answer:

    Use JavaScript runtime checks like typeof to distinguish types and process accordingly. -> Option B
  5. Quick Check:

    Runtime type safety = typeof checks [OK]
Hint: Always check types at runtime with typeof for unions [OK]
Common Mistakes:
  • Assuming TypeScript types exist at runtime
  • Using instanceof with primitives
  • Ignoring runtime type checks
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