Basic Types
TypeScript ke core primitive types hain string, number, aur boolean. Aap ek variable ka type colon ke sath explicitly annotate kar sakte ho, halaanki TypeScript aksar type khud hi figure out kar leta hai.
let username: string = "Alice"; let age: number = 30; let isStudent: boolean = false; console.log(username, typeof username); console.log(age, typeof age); console.log(isStudent, typeof isStudent);
Alice string 30 number false boolean
Type inference
Aapko har variable ko annotate karne ki zaroorat nahi hai — agar aap ek variable ko initial value dete ho, TypeScript us value se uska type automatically infer kar leta hai, aur baad mein mismatch ko bilkul waise hi pakad lega jaise aapne khud annotation likhi ho.
let city = "Tokyo"; // inferred as string, no annotation needed console.log(city, typeof city);
Tokyo string
Ek real type error kaisa dikhta hai
Yeh genuinely woh hai jo TypeScript ka compiler output karta hai jab aap galat type assign karne ki koshish karte ho — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:
let score: string = "high"; score = 42; console.log(score);
script.ts(2,1): error TS2322: Type '42' is not assignable to type 'string'.
Kuch bhi run nahi hota — koi output nahi, bas error. Yahi poora point hai: TypeScript aapko yahin rok deta hai, ek galat-typed value ko chup chaap aapke program mein kahin aur problem create karne dene ke bajaye.
Aage: arrays aur tuples — typed collections, aur ek aisa TypeScript-only structure jiska koi real JavaScript equivalent nahi hai.