Day 67

TypeScript Basics

14 min
JavaScript 100 Days

TypeScript JavaScript ka superset hai jisme static typing add hoti hai. Types se bugs compile time par pakde jaate hain — runtime errors kam hote hain. React, Next.js — sab TypeScript use karte hain.

TypeScript Setup & Basic Types

TypeScript install karo aur types likhna seekho.

basics.ts
typescript
// npm install -g typescript
// tsc --init (tsconfig.json)

// Basic types
let name: string = "Zohaib";
let age: number = 25;
let isStudent: boolean = false;
let scores: number[] = [85, 92, 78];
let tuple: [string, number] = ["Lahore", 2024];

// Any — use sparingly
let anything: any = "can be anything";

// Function types
function greet(name: string, age: number): string {
  return `Hello ${name}, you are ${age} years old`;
}

// Optional parameters
function createUser(name: string, email?: string): object {
  return { name, email: email ?? "not provided" };
}

// Union types
let id: string | number;
id = "abc-123";
id = 123; // both valid!

// Compile: tsc basics.ts → basics.js

🎯 Practice Challenge

Calculator TypeScript mein banao — har function properly typed ho. Generic calculator function banao jo kisi bhi numeric type support kare.