0
0
Typescriptprogramming~5 mins

Type erasure and its consequences in Typescript

Choose your learning style9 modes available
Introduction

Type erasure means TypeScript removes all type information when it turns your code into JavaScript. This helps your code run in any browser or environment that understands JavaScript.

When you want to write safer code with types but still run it anywhere JavaScript runs.
When you use generics to write reusable functions or classes but don't want types to affect runtime.
When debugging, to understand why type info is missing in the running code.
When integrating TypeScript code with plain JavaScript libraries or tools.
Syntax
Typescript
function identity<T>(arg: T): T {
  return arg;
}

Type parameters like <T> exist only during development and are removed in the final JavaScript.

At runtime, TypeScript code behaves like plain JavaScript without type checks.

Examples
This generic function returns whatever you give it. The T is a placeholder for any type.
Typescript
function identity<T>(arg: T): T {
  return arg;
}
Here, we tell TypeScript that T is a number. But at runtime, this is just identity(42).
Typescript
const result = identity<number>(42);
console.log(result);
Type erasure means you can't check types at runtime, so you must be careful with properties that might not exist.
Typescript
function logLength<T>(arg: T): T {
  // console.log(arg.length); // Error: length might not exist
  return arg;
}
Sample Program

This program shows a generic function that returns the input. Types help during coding but disappear when running.

Typescript
function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(123);
const str = identity<string>("hello");

console.log(num);
console.log(str);
OutputSuccess
Important Notes

Type erasure means you cannot use types to check or change behavior at runtime.

Be careful with assumptions about types when your code runs, because type info is gone.

Use runtime checks (like typeof) if you need to verify types while running.

Summary

TypeScript removes all type info when creating JavaScript code.

Types help you write safer code but do not exist when the code runs.

You must use JavaScript checks if you want to test types at runtime.