AnyCompiler

Basic Types

TypeScript ke core primitive types hain string, number, aur boolean. Aap ek variable ka type colon ke sath explicitly annotate kar sakte hain, halaanke 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);
Output
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 hain, TypeScript us value se uska type khud ba khud infer kar leta hai, aur baad mein mismatch ko bilkul waise hi pakar lega jaise aap ne khud annotation likhi ho.

let city = "Tokyo"; // inferred as string, no annotation needed
console.log(city, typeof city);
Output
Tokyo string

Ek real type error kaisa dikhta hai

Yeh waqai woh hai jo TypeScript ka compiler output karta hai jab aap ghalat type assign karne ki koshish karte hain — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:

let score: string = "high";
score = 42;
console.log(score);
Output
script.ts(2,1): error TS2322: Type '42' is not assignable to type 'string'.

Kuch bhi nahi chalta — koi output nahi, bas error. Yehi poora point hai: TypeScript aapko yahin rok deta hai, ek ghalat-typed value ko khamoshi se aapke program mein kahin aur masla create karne dene ke bajaye.

Aage: arrays aur tuples — typed collections, aur ek aisa TypeScript-only structure jiska koi real JavaScript equivalent nahi hai.