Course contentsShow
← TypeScript
Lesson 1281 of 1,79630. Type-Safe APIsFree lesson

The Gap Between Types and Runtime

Understanding that TypeScript types disappear at runtime, and why type assertions alone don't protect you from bad data.

The Gap Between Types and Runtime

What you'll learn: You'll understand why TypeScript types are erased at runtime and why type assertions alone can't protect your code from invalid data.

The Fundamental Illusion

Here's the uncomfortable truth about TypeScript: all your types disappear when your code runs. TypeScript exists only during development and compilation. Once tsc transpiles your TypeScript to JavaScript, every type annotation, interface, and type assertion vanishes completely.

Think of TypeScript types like a security checkpoint at an airport. They verify everything before the flight, but once you're in the air, those checks aren't happening anymore. If someone smuggled something past security (or if you bypassed security entirely), you won't find out until it's too late.

The Runtime Reality

When you write a type assertion like const user = data as User, you're not actually checking anything. You're simply telling TypeScript's compiler: "Trust me, this is a User." The compiler believes you and stops complaining. But at runtime, JavaScript has no idea what a User type is — that concept doesn't exist in the generated code.

This creates a dangerous scenario: TypeScript thinks your data is safe based on your assertion, but if the actual data doesn't match that shape (say, from an API that changed its response format), your code will crash or behave unpredictably.

Why This Matters for APIs

This gap becomes critical when working with external data from APIs, user input, or file systems. The data entering your application hasn't been type-checked by TypeScript. If you blindly cast it to your expected type, you're building on sand. You need runtime validation — actual JavaScript code that checks the data's structure — not just compile-time types.

Key Takeaway: TypeScript types are design-time documentation and compile-time guards, but they provide zero runtime protection. Type assertions tell the compiler what you hope is true, not what actually is true.