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

Overriding Incompatible Types

Use double assertions to force conversions between structurally incompatible types.

Overriding Incompatible Types

What you'll learn: How to force TypeScript to accept type conversions between structurally incompatible types using double assertions.

The Problem: When TypeScript Says "No Way"

You've learned that single type assertions (as SomeType) let you tell TypeScript "trust me, I know this is that type." But sometimes TypeScript refuses even that. When types are structurally incompatible—meaning they share no overlap whatsoever—TypeScript blocks direct assertions to protect you from obvious mistakes.

type Cat = { meow: () => void };
type Engine = { horsepower: number };

const myCat: Cat = { meow: () => console.log("meow") };

// ❌ Error: Conversion may be a mistake
const engine = myCat as Engine;

TypeScript sees no common ground between Cat and Engine, so it rejects this assertion outright.

The Double Assertion Technique

When you really need to override TypeScript's safety checks, you can perform a double assertion (also called a "double cast"):

const engine = myCat as unknown as Engine;

This works because:

  1. First assertion (as unknown): Any type can be asserted to unknown (the top type)
  2. Second assertion (as Engine): unknown can be asserted to any type

Think of unknown as a neutral intermediate step—a "type transit station" where any type can connect.

Why This Works

The unknown type accepts all values and can be narrowed to anything. By routing through unknown, you're essentially saying: "TypeScript, temporarily forget everything about this value's structure, then let me reinterpret it completely."

When This Might Be Legitimate

  • Testing/mocking: Creating fake objects that don't fully implement interfaces
  • Interfacing with untyped legacy code where you know the runtime structure differs from types
  • Type system limitations: Rare cases where correct runtime code can't be expressed in TypeScript's type system

The Giant Warning Label

Double assertions are extremely dangerous. You're disabling all type safety between two unrelated types. If you're wrong about the runtime structure, you'll get runtime crashes with no compiler protection.

This should be a last resort, not a habit. Almost always, there's a better solution: fixing the types, using proper type guards, or restructuring your code.

Key Takeaway: Double assertions (value as unknown as TargetType) force conversions between incompatible types by routing through unknown, but they completely bypass type safety and should be used only when absolutely necessary.