TypeScript Casting

TypeScript tutorial

🔁 TypeScript Casting (Type Assertions)

TypeScript Casting (officially called Type Assertions) is used when you want to tell TypeScript the exact type of a value.

📌 Casting does not change the value at runtime
It only helps the TypeScript compiler understand your intent

1️⃣ Why Type Casting is Needed

Sometimes TypeScript cannot infer the correct type.

let value: unknown = "Hello TypeScript";

// Error ❌
// console.log(value.toUpperCase());

Casting fixes this:

console.log((value as string).toUpperCase());

2️⃣ as Syntax (Recommended ⭐)

let input: unknown = "Sanjit";

let length = (input as string).length;

✔ Clean
✔ Preferred in modern TypeScript

3️⃣ Angle Bracket Syntax

let input: unknown = "TypeScript";

let length = (<string>input).length;

⚠️ Not allowed in .tsx (React) files.

4️⃣ Casting with DOM Elements (Very Common)

const inputEl = document.getElementById("username") as HTMLInputElement;

console.log(inputEl.value);

Without casting:

// Property 'value' does not exist on type 'HTMLElement'

5️⃣ Casting unknown to a Specific Type

let data: unknown = "123";

let num = Number(data as string);

6️⃣ Casting Between Compatible Types

let x = "100" as unknown as number;

⚠️ Avoid double casting unless absolutely required.

7️⃣ Casting Arrays

let values: unknown = ["A", "B", "C"];

let names = values as string[];

8️⃣ Casting Objects

type User = {
name: string;
age: number;
};
let obj: unknown = {
name: “Sanjit”,
age: 25
};let user = obj as User;

9️⃣ Unsafe Casting (Be Careful ❌)

let num = "hello" as number; // No compile error, but runtime bug

📌 TypeScript trusts you blindly during casting.

🔑 Casting Summary

SyntaxUse Case
as TypeRecommended
<Type>Not for TSX
DOM CastingHTML elements
unknown → typeSafe casting
Double CastAvoid

⭐ Best Practices

✔ Prefer type narrowing over casting
✔ Use casting only when you are sure
✔ Avoid casting from unrelated types
✔ Avoid excessive any + casting

You may also like...