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

Assertions Are Not Casts

Type assertions don't change runtime behavior or convert values—they only affect compile-time type checking.

Assertions Are Not Casts

You'll learn: Type assertions in TypeScript only change how the compiler sees a value—they don't transform or convert the actual data at runtime.

The Critical Misconception

Many developers coming from languages like C++ or C# expect TypeScript's as syntax to convert values, like a cast would. This is wrong. Type assertions are purely a compile-time instruction that tells TypeScript: "Trust me, I know better than you about this value's type."

When your code compiles to JavaScript, all type assertions completely disappear. They generate zero runtime code.

What Actually Happens

const input = "42";

// This assertion doesn't convert anything
const num = input as number;

console.log(typeof num); // Still "string" at runtime!
console.log(num + 10);   // "4210" (string concatenation, not 52)

The as number assertion didn't magically turn the string "42" into the number 42. It simply told the compiler to stop complaining and treat input as a number for type-checking purposes. The JavaScript that runs is exactly the same as if you'd written:

const input = "42";
const num = input;

The Compile-Time vs Runtime Divide

Type assertions exist in a different dimension than your actual data:

const obj = { name: "Alice" } as { name: string; age: number };

// TypeScript thinks obj.age exists
console.log(obj.age.toFixed(2)); // Compiles fine!

// Runtime: TypeError - Cannot read property 'toFixed' of undefined

TypeScript allowed this code because you asserted the shape. But at runtime, obj.age is still undefined—no assertion can conjure properties into existence.

Why Assertions Exist

Assertions aren't for conversion—they're for situations where you have information the type system doesn't:

const userInput = document.getElementById("name") as HTMLInputElement;
// The DOM API returns HTMLElement | null
// But YOU know this ID points to an input

If you need actual conversion, write runtime code:

const str = "42";
const num = Number(str); // Real conversion: string → number

Key Takeaway: Type assertions are compiler hints, not data transformations. They affect type checking only—never the actual values your code manipulates at runtime. If you need to change a value's type, you need runtime conversion code, not an assertion.