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

The Shape Mismatch Problem

APIs, databases, and user input can send anything; types alone don't prevent runtime errors from bad data.

The Shape Mismatch Problem

What you'll learn: Why TypeScript's types alone cannot protect you from runtime errors caused by external data that doesn't match your expected shape.

The Core Problem

TypeScript's type system is a compile-time tool. It analyzes your code before it runs and ensures that the types you've declared are used consistently throughout your application. However, there's a fundamental gap: TypeScript has no control over data that comes from outside your program.

When you fetch data from an API, read from a database, or accept user input, you're receiving information from sources that exist beyond TypeScript's reach. The database doesn't know about your TypeScript types. The API server doesn't validate against your interfaces. The user typing into a form field has no idea what shape of data your code expects.

The Illusion of Safety

Consider this: you define an interface for a user object with name: string and email: string. You write a function that accepts this type. TypeScript checks that you're using it correctly. Everything compiles successfully.

But at runtime, your API returns { username: string, contact: string } instead. Or the email field is missing entirely. Or what you expected to be a string is actually null.

Your types promised one shape. Reality delivered another. TypeScript can't prevent this mismatch because it doesn't execute at runtime—it only validates the code you wrote, not the data that flows through it.

Why This Matters

The shape mismatch problem is why type assertions and runtime validation exist. Your types describe your expectations and help you write correct code internally. But they're essentially a contract with yourself, not an enforced guarantee about the outside world. When external data enters your system, you must verify it actually matches the shape your types claim it has.

Key Takeaway: TypeScript types are compile-time documentation and internal validation—they cannot verify that runtime data from APIs, databases, or users actually matches the shapes you've declared.