Type Inference and Assertions
How TypeScript automatically guesses types, and how you can override them using type assertions.
🧑🏫 Sabse pehle — simple mein samjho#
TypeScript bahut smart hai. Tumhe har baar explicitly (bol-bol ke) type batane ki zaroorat nahi hai. Agar tumne likha let age = 25;, TS khud samajh jayega ki yeh number hai. Isko Type Inference (andaza lagana) kehte hain. Par kabhi kabhi TS ko poori picture nahi dikhti (jaise DOM elements select karte waqt ya API se data aate waqt). Wahan hum Type Assertion (as keyword) use karke TS ko kehte hain, "Chup chap maan lo jo main bol raha hoon, I know what I am doing".
Type Inference#
If you assign a value to a variable during initialization, you don't need to explicitly state its type. TypeScript will automatically infer it.
// ❌ Redundant (unnecessary explicit typing)
let myName: string = "Tarun";
// ✅ Smart (Inference)
let myName = "Tarun"; // TS automatically knows this is a string
// It works for arrays too
let numbers = [1, 2, 3]; // TS infers: number[]
// It works for function return types
function add(a: number, b: number) {
return a + b; // TS knows that number + number = number
}
Note: If you declare a variable without initializing it, TS will assign it the any type, which is dangerous.
let something; // Inferred as `any`
something = "Hello";
something = 42; // No error 😢
// You should provide an explicit type here
let age: number;
Type Assertion (as keyword)#
Sometimes you have more information about a value than TypeScript does. The most common scenario is DOM manipulation.
// TS thinks: This could be any HTMLElement, or it could be null.
const myInput = document.getElementById("main-input");
// myInput.value // ❌ ERROR: Object is possibly 'null'. Property 'value' does not exist on type 'HTMLElement'.
// Using Type Assertion
const myInput = document.getElementById("main-input") as HTMLInputElement;
// Now TS is "convinced" that this is definitely an input field
console.log(myInput.value); // ✅ No error
Alternative Syntax (Angle Brackets)#
You should avoid using the angle bracket syntax in React (TSX) because it conflicts with JSX elements. Always prefer the as keyword.
// Not recommended in React
const myInput = <HTMLInputElement>document.getElementById("main-input");
Double Assertion (The Danger Zone)#
If you want to forcefully convert a type to a completely unrelated type, you have to cast it to unknown first. This should be used sparingly.
let userId = 123;
// let stringId = userId as string; // ❌ ERROR: TS refuses this direct conversion
let stringId = userId as unknown as string; // ✅ Forcefully done