Course contentsShow
← TypeScript
Lesson 999 of 1,79623. Type AssertionsFree lesson

Runtime Safety Considerations

Understand that double assertions completely bypass type safety and require runtime validation.

Runtime Safety Considerations

What you'll learn: How double assertions create a complete bypass of TypeScript's safety system and why runtime validation becomes essential.

The Core Problem

When you use a double assertion (like value as unknown as SomeType), you're telling TypeScript: "Trust me completely, ignore everything you know." TypeScript will allow this conversion from any type to any other type, even when it makes zero logical sense.

Here's the critical truth: TypeScript types disappear at runtime. When your code actually executes, all those type assertions vanish—they're purely compile-time instructions. The double assertion doesn't transform your data; it only silences the compiler.

The Safety Gap

Imagine you have incoming data:

const apiData: unknown = fetchSomeData();

// This compiles without error:
const user = apiData as unknown as { name: string; age: number };

// But at runtime, apiData might be:
// - null
// - an array
// - a string
// - an object with completely different properties

TypeScript believes user.name is a string now. You'll get autocomplete. No red squiggles. But if apiData was actually null, your code crashes with Cannot read property 'name' of null.

Protecting Yourself

Since TypeScript can't help you after a double assertion, you must validate at runtime:

function isValidUser(value: unknown): value is { name: string; age: number } {
  return (
    typeof value === 'object' &&
    value !== null &&
    'name' in value &&
    typeof (value as any).name === 'string' &&
    'age' in value &&
    typeof (value as any).age === 'number'
  );
}

if (isValidUser(apiData)) {
  // Now TypeScript AND runtime reality agree
  console.log(apiData.name);
}

Key Takeaway: Double assertions bypass all type safety—TypeScript cannot protect you from runtime errors afterward. Always add explicit runtime validation when you override the type system this aggressively, especially for external data sources.