TypeScript Basics — JavaScript Developers Ke Liye Roman Urdu Guide
TypeScript ka complete beginner guide JavaScript developers ke liye. Types, interfaces, generics, React mein use — sab kuch examples ke saath Roman Urdu mein.
TypeScript Basics — JavaScript Developers Ke Liye Guide
2026 mein TypeScript NOT optional hai — har serious React/Next.js project mein use ho raha hai. Pakistan mein bhi top companies (VentureDive, 10Pearls, Tintash) TypeScript skill explicitly maangti hain.
Agar tum JavaScript jaante ho lekin TypeScript se darte ho — ye guide tumhare liye hai. 2 ghante mein basics master kar lo ge.
ℹ️ 📚 Prerequisites
- ✅ JavaScript fundamentals (variables, functions, objects, arrays)
- ✅ Node.js + npm installed
- ✅ VS Code / Cursor IDE
- ❌ Pichla TypeScript experience: zero zaroori nahi
1. TypeScript Kya Hai?
TypeScript = JavaScript + Types
Microsoft ne 2012 mein banaya — JavaScript ke saare features support karta hai plus type safety add karta hai.
TypeScript (Microsoft)
JavaScript ka superset — types ke saath safer code
Simple Example:
JavaScript (no safety):
function greet(name) {
return "Hello, " + name.toUpperCase();
}
greet("Babar"); // Works fine
greet(123); // Crashes at runtime! 💥TypeScript (safety):
function greet(name: string): string {
return "Hello, " + name.toUpperCase();
}
greet("Babar"); // ✅ Works
greet(123); // ❌ Error at compile time (catches bug early!)Bottom line: TypeScript bugs pehle pakad leta hai — production mein crash hone se pehle.
2. Why Use TypeScript? — Real Benefits
Reason 1: Bug Prevention
Types enforce karte hain code ka structure — common bugs auto-detect ho jate hain.
Reason 2: Better Autocomplete
VS Code/Cursor mein TypeScript ke saath god-tier autocomplete milta hai:
- Variable types instantly dikhte hain
- Function parameters auto-suggested
- Refactoring 10x easier
Reason 3: Industry Standard
2026 Job Listings (Pakistan):
React Jobs: 90% require TypeScript
Next.js Jobs: 95% require TypeScript
Senior Jobs: 100% require TypeScript
Reason 4: Better Documentation
Code khud documenting ho jata hai:
// Reader instantly samjhta hai
function calculateTotal(
items: Product[],
discount: number,
taxRate: number
): number {
// ...
}vs
// Reader confused — kya kya pass karna hai?
function calculateTotal(items, discount, taxRate) {
// ...
}3. Setup — 5 Minutes Mein
Install TypeScript Globally:
npm install -g typescript
# Verify installation
tsc --versionCreate New TypeScript Project:
mkdir my-ts-project
cd my-ts-project
npm init -y
npm install --save-dev typescript @types/node
# Create config
npx tsc --initFirst TypeScript File:
hello.ts banao:
const name: string = "Babar";
const age: number = 25;
const isStudent: boolean = false;
function introduce(personName: string, personAge: number): string {
return `Hi, I'm ${personName}, ${personAge} years old.`;
}
console.log(introduce(name, age));Compile + Run:
tsc hello.ts # Generates hello.js
node hello.js # Runs the JavaScript🎯 Auto-Compile
ts-node install karo — TypeScript directly run ho jati hai (compile step skip):
npm install -g ts-node
ts-node hello.ts # Direct run!4. Basic Types — Building Blocks
Primitive Types:
let username: string = "babar";
let age: number = 25;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;Arrays:
// Two ways — same meaning:
let scores: number[] = [85, 90, 78];
let names: Array<string> = ["Ali", "Sara", "Hassan"];
// Mixed types — use union (later):
let mixed: (string | number)[] = ["hello", 42, "world"];Tuples (Fixed-length arrays):
let person: [string, number] = ["Babar", 25];
// Order matters!
let coordinates: [number, number, number] = [10, 20, 30];Objects:
let user: {
name: string;
age: number;
email: string;
} = {
name: "Babar",
age: 25,
email: "babar@example.com"
};ℹ️ ℹ️ Type Inference
TypeScript smart hai — agar value se type clear hai to explicit type likhne ki zaroorat nahi:
let name = "Babar"; // TypeScript automatically samjh leta hai: string
let age = 25; // Auto-inferred: numberLekin function parameters always explicit likhne chahiye.
5. Interfaces — Reusable Object Shapes
Same object structure baar baar use karna hai? Interface banao:
interface User {
name: string;
age: number;
email: string;
isAdmin?: boolean; // ? = optional
}
const user1: User = {
name: "Babar",
age: 25,
email: "babar@example.com"
// isAdmin optional — skip kar sakte ho
};
const user2: User = {
name: "Sara",
age: 22,
email: "sara@example.com",
isAdmin: true
};Interface Methods:
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
const myCalc: Calculator = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};Interface Extension:
interface Animal {
name: string;
age: number;
}
interface Dog extends Animal {
breed: string;
bark(): void;
}
const myDog: Dog = {
name: "Rex",
age: 3,
breed: "Labrador",
bark: () => console.log("Woof!")
};6. Type Aliases — Interface Ka Cousin
Type aliases interfaces se similar hain but more flexible:
type UserID = string | number; // Union type
type Status = "active" | "inactive" | "pending"; // Literal types
type User = {
id: UserID;
name: string;
status: Status;
};
const user: User = {
id: "user_123", // Or could be: 123
name: "Babar",
status: "active" // Must be one of the three values
};Interface vs Type — Kab Konsa Use Karein?
| Feature | Interface | Type |
|---|---|---|
| Object shapes | ✅ Best | ✅ Good |
| Extension | extends keyword | & intersection |
| Union types | ❌ Can't | ✅ Yes |
| Primitives/Literals | ❌ Can't | ✅ Yes |
| Declarative merge | ✅ Yes | ❌ No |
🎯 Rule of Thumb
Objects ke liye → interface use karo
Unions/Literals/Complex types → type use karo
7. Functions With Types
Basic Function:
function add(a: number, b: number): number {
return a + b;
}
// Arrow function version:
const multiply = (a: number, b: number): number => a * b;Optional Parameters:
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}`;
}
return `Hello, ${name}`;
}
greet("Babar"); // "Hello, Babar"
greet("Babar", "Dr."); // "Hello, Dr. Babar"Default Parameters:
function createUser(
name: string,
role: string = "user",
isActive: boolean = true
) {
return { name, role, isActive };
}
createUser("Babar");
// { name: "Babar", role: "user", isActive: true }Function Return Types:
// void = nothing returned
function logMessage(msg: string): void {
console.log(msg);
}
// never = function never returns (throws error)
function throwError(msg: string): never {
throw new Error(msg);
}8. Union & Intersection Types
Union Types (| — Or):
type ID = string | number; // Either string OR number
function printID(id: ID) {
console.log(`ID: ${id}`);
}
printID("user_123"); // ✅
printID(123); // ✅
printID(true); // ❌ ErrorIntersection Types (& — And):
type Employee = {
id: string;
salary: number;
};
type Person = {
name: string;
age: number;
};
type StaffMember = Employee & Person; // Has all properties
const staff: StaffMember = {
id: "emp_001",
salary: 50000,
name: "Babar",
age: 25
};9. Generics — Reusable Types
Generic types flexibility + safety dono dete hain:
Without Generics (Bad):
function getFirstItem(items: any[]) {
return items[0]; // Returns 'any' - no type safety
}
const num = getFirstItem([1, 2, 3]);
num.toUpperCase(); // Crashes — 1 pe toUpperCase nahi!With Generics (Good):
function getFirstItem<T>(items: T[]): T {
return items[0];
}
const num = getFirstItem([1, 2, 3]);
// num is automatically: number
// num.toUpperCase() — Error at compile time! ✅
const name = getFirstItem(["Babar", "Sara"]);
// name is automatically: string
// name.toUpperCase() — Works! ✅Real-World Generic Example:
interface ApiResponse<T> {
success: boolean;
data: T;
error?: string;
}
// User API response
const userResponse: ApiResponse<User> = {
success: true,
data: { name: "Babar", age: 25, email: "..." }
};
// Products API response
const productsResponse: ApiResponse<Product[]> = {
success: true,
data: [{ id: "1", name: "Laptop", price: 1000 }]
};10. TypeScript in React/Next.js
Component Props:
interface ButtonProps {
label: string;
onClick: () => void;
variant?: "primary" | "secondary";
disabled?: boolean;
}
function Button({ label, onClick, variant = "primary", disabled = false }: ButtonProps) {
return (
<button
onClick={onClick}
disabled={disabled}
className={`btn btn-${variant}`}
>
{label}
</button>
);
}
// Usage:
<Button
label="Click Me"
onClick={() => alert("Clicked!")}
variant="primary"
/>useState With Types:
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<Product[]>([]);Event Handlers:
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
// ...
}
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setValue(e.target.value);
}Next.js 16 Pages With Types:
// app/blog/[slug]/page.tsx
interface Props {
params: Promise<{ slug: string }>;
}
export default async function BlogPost({ params }: Props) {
const { slug } = await params;
return <h1>Post: {slug}</h1>;
}11. Common Mistakes — Avoid Karein
🚫 ❌ Beginner Mistakes
anyoveruse — har jagahanyuse karna defeats TypeScript ka purpose- Type assertions abuse (
as) — type incorrect ho to bypass mat karo - Optional chaining without types — types use karo to know what's optional
@ts-ignoreeverywhere — agar zaroorat hai to comment add karo whyFunctiontype use karna — specific signature likho ((a: number) => string)Objecttype — bohat generic hai, specific interface use karo- Implicit
anyenable rakhna —strict: trueuse karo always
Bad vs Good:
Bad:
let data: any = fetchData();
data.user.name.toUpperCase(); // No safety!Good:
interface ApiData {
user: {
name: string;
email: string;
};
}
const data: ApiData = await fetchData();
data.user.name.toUpperCase(); // Safe!12. Type Narrowing — Smart TypeScript
TypeScript automatically narrow karta hai types based on checks:
function processValue(value: string | number) {
if (typeof value === "string") {
// TypeScript jaanta hai: value is string here
console.log(value.toUpperCase());
} else {
// TypeScript jaanta hai: value is number here
console.log(value.toFixed(2));
}
}Discriminated Unions:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}13. TSConfig — Configuration Basics
tsconfig.json mein important settings:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true, // ⭐ ENABLE!
"esModuleInterop": true,
"skipLibCheck": true,
"noImplicitAny": true, // ⭐ No implicit any
"strictNullChecks": true, // ⭐ null/undefined safety
"noUnusedLocals": true, // Remove unused code
"noUnusedParameters": true
}
}🎯 Always Use Strict Mode
"strict": true enable karo hamesha. Beginners ko initially mushkil lagti hai, lekin 2 hafte mein bohat behtar developer ban jate ho — TypeScript ka full benefit yahi se aata hai.
14. TypeScript Roadmap — 2 Hafte Mein Master
Day 1-3: Basics
- ✅ Types: string, number, boolean
- ✅ Arrays, objects, tuples
- ✅ Type inference
Day 4-7: Intermediate
- ✅ Interfaces, type aliases
- ✅ Union/intersection types
- ✅ Function types
Day 8-10: Advanced
- ✅ Generics
- ✅ Type narrowing
- ✅ Discriminated unions
Day 11-14: React/Next.js Integration
- ✅ Component props with types
- ✅ Hooks with types
- ✅ Event handlers
- ✅ API responses
15. Resources — Aage Padhne Ke Liye
Free Resources:
- Official Docs: typescriptlang.org/docs
- TypeScript Playground: typescriptlang.org/play (browser mein experiment)
- Total TypeScript: Matt Pocock's free articles
- YouTube: "TypeScript Crash Course" by Brad Traversy
AI-Powered Learning:
Modern way: Claude AI ya ChatGPT se TypeScript seekho:
"Mujhe TypeScript ka generic type explain karo Roman Urdu mein,
React component example ke saath."
AI tutorial personalized + interactive hota hai.
🎯 Practice Project Ideas
Week 1 Projects:
- ✅ Todo App — basic types + interfaces
- ✅ Calculator — function types
- ✅ Number guesser game — type narrowing
Week 2 Projects:
- ✅ Weather app — API responses with generics
- ✅ Blog system — Next.js + TypeScript
- ✅ E-commerce cart — complex state with TypeScript
🎓 Related Posts
- Next.js 16 Complete Beginner Guide (TypeScript Next.js mein use)
- JavaScript Async/Await Asaan Tarike Se (TS sehre js hai)
- Cursor AI Complete Guide (TypeScript autocomplete master)
- CS Graduate Pakistan Job Guide (TS = job market mein zaroori)
TypeScript seekhne mein koi confusion? Comment mein specific question karo — main solve kar dunga.
Pakistani devs ke saath share karo — TypeScript skills 2026 mein game-changer hain 🇵🇰
Happy Coding! 📘
Written by UrduCoder
Pakistan ka #1 Roman Urdu coding blog. Hum AI, Web Dev, aur tech tutorials publish karte hain har hafte.
Related Posts
Next.js 14 Complete Course - Roman Urdu Mein Seekho
Next.js 14 ka A-to-Z course Roman Urdu mein. App Router, Server Components, aur modern web development ki har cheez.
Next.js 16 Complete Beginner Guide — Roman Urdu Mein Seekho
Next.js 16 ka complete beginner guide Roman Urdu mein. Turbopack, App Router, Server Components, React 19, async params — sab kuch step-by-step examples ke saath.
React Hooks Complete Guide 2026 — Roman Urdu Mein Seekho
React hooks ka complete guide Roman Urdu mein. useState, useEffect, useContext, useMemo, useCallback, useRef, custom hooks — sab kuch examples ke saath.