🚀 Cyber Security New Batch Start from 1 JunEnroll Now
Cyber Defence
Development

TypeScript Tutorial: JavaScript with Types — Complete Beginner Guide 2026

Complete TypeScript tutorial for beginners. Learn TypeScript from scratch in 2026 — types, interfaces, generics, decorators, and how to use TypeScript with React and Node.js with practical code examples.

Amit Kumar
Amit KumarEthical Hacker & Founder
7 min read
TypeScript Tutorial: JavaScript with Types — Complete Beginner Guide 2026 TypeScript JavaScript ka superset hai jo static typing introduce karta hai. Yeh complete TypeScript tutorial aapko basics se lekar advanced features tak le jayega with practical examples jo aap real projects mein use kar sakte ho. ## TypeScript Kya Hai TypeScript Microsoft dwara develop kiya gaya ek programming language hai jo JavaScript par built hai. Yeh aapko compile-time par errors catch karne ki facility deta hai — jo runtime errors ko significantly reduce karta hai. TypeScript ka code JavaScript mein compile hota hai (transpiled) so aap kahin bhi JS use kar sakte ho. ### Why TypeScript? - Error Prevention: Bugs compile time par hi catch ho jate hain - Better IDE Support: Autocomplete aur type checking - Self-Documenting Code: Types se code apna aap document karta hai - Refactoring Made Easy: Types safe changes ensure karte hain - Team Collaboration: Clear contracts between components ## TypeScript Setup ### Installation npm se TypeScript install karein: npm install -g typescript Check version: tsc --version Project mein local install: npm install --save-dev typescript TypeScript config file banana: npx tsc --init ### tsconfig.json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "lib": ["ES2020", "DOM"], "moduleResolution": "node", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "jsx": "react-jsx" }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ## TypeScript Types Tutorial ### Basic Types // String let name: string = "Cyber Defence"; let greeting: string = 'Hello, World!'; // Number let age: number = 25; let price: number = 99.99; let hex: number = 0xff; // Boolean let isActive: boolean = true; let isLoading: boolean = false; // Array let numbers: number[] = [1, 2, 3, 4, 5]; let names: string[] = ["Alice", "Bob", "Charlie"]; let mixed: Array = [1, "two", 3]; // Tuple - Fixed length, fixed types let user: [string, number, boolean] = ["Alice", 25, true]; let rgb: [number, number, number] = [255, 128, 0]; // Enum enum Status { Active, Inactive, Pending } let currentStatus: Status = Status.Active; // Any - Avoid when possible let anything: any = "can be anything"; anything = 42; anything = true; // Unknown - Safer alternative to any let unknownValue: unknown = "some value"; if (typeof unknownValue === "string") { console.log(unknownValue.toUpperCase()); } // Void - Function returns nothing function logMessage(message: string): void { console.log(message); } // Never - Function never returns function throwError(message: string): never { throw new Error(message); } ## TypeScript Interfaces aur Types ### Interface Definition // Basic Interface interface User { id: number; name: string; email: string; age?: number; // Optional property readonly createdAt: Date; // Read-only property } // Interface with method interface UserWithMethod { id: number; name: string; greet(): string; } // Interface extending another interface Admin extends User { role: 'superadmin' | 'admin' | 'moderator'; permissions: string[]; } // Implementing interface in class class UserClass implements User { id: number; name: string; email: string; readonly createdAt: Date; constructor(id: number, name: string, email: string) { this.id = id; this.name = name; this.email = email; this.createdAt = new Date(); } greet(): string { return "Hello, my name is " + this.name; } } ### Type Aliases // Simple type alias type UserId = number; type Username = string; // Object type type UserProfile = { id: number; name: string; bio: string; avatar?: string; followers: number; following: number; }; // Union types type Status = 'pending' | 'active' | 'inactive' | 'deleted'; type Result = SuccessResponse | ErrorResponse; // Intersection types type Employee = { employeeId: string; department: string; }; type Manager = { teamSize: number; }; type TeamLead = Employee & Manager; // Utility types type PartialUser = Partial; type RequiredUser = Required; type ReadonlyUser = Readonly; type PickUser = Pick; type OmitUser = Omit; ## TypeScript Generics Tutorial Generics aapko reusable components banana ki facility dete hain jo multiple types ke saath kaam kar sakein. ### Generic Functions // Generic function function identity(value: T): T { return value; } console.log(identity("Hello")); console.log(identity(42)); console.log(identity(true)); console.log(identity("Auto-inferred")); // Multiple type parameters function pair(key: K, value: V): [K, V] { return [key, value]; } const userPair = pair("user", { name: "Alice", age: 25 }); // Generic constraints interface HasLength { length: number; } function logLength(item: T): number { return item.length; } logLength("Hello"); // String - OK logLength([1, 2, 3]); // Array - OK logLength({ length: 10 }); // Object with length - OK ### Generic Interfaces // Generic interface interface ApiResponse { data: T; status: number; message: string; timestamp: Date; } interface User { id: number; name: string; } const userResponse: ApiResponse = { data: { id: 1, name: "Alice" }, status: 200, message: "Success", timestamp: new Date() }; // Generic class class DataStore { private items: T[] = []; add(item: T): void { this.items.push(item); } get(index: number): T | undefined { return this.items[index]; } getAll(): T[] { return [...this.items]; } get count(): number { return this.items.length; } } ## TypeScript with React Tutorial React Component with TypeScript: import React, { useState, useEffect } from 'react'; // Props interface interface CardProps { title: string; description: string; imageUrl?: string; tags: string[]; onClick?: () => void; } // Component with typed props const Card = ({ title, description, imageUrl, tags, onClick }) => { const [isExpanded, setIsExpanded] = useState(false); return (
{imageUrl && {title}}

{title}

{description}

{tags.map(tag => ( {tag} ))}
); }; Hook with types: interface Post { id: number; title: string; body: string; userId: number; } function usePosts() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then(res => res.json()) .then((data) => { setPosts(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); return { posts, loading, error }; } ## TypeScript Best Practices 2026 1. Use strict mode - tsconfig.json mein "strict": true rakhna 2. Avoid 'any' - use 'unknown' instead function processData(data: unknown) { if (typeof data === 'string') { console.log(data.toUpperCase()); } } 3. Use union types over enums where appropriate type Direction = 'north' | 'south' | 'east' | 'west'; 4. Use readonly for immutable data interface Config { readonly apiUrl: string; readonly maxRetries: number; } 5. Use optional chaining const userName = user?.profile?.name ?? 'Anonymous'; 6. Use nullish coalescing const fallback = value ?? 'default'; 7. Type guard functions function isString(value: unknown): value is string { return typeof value === 'string'; } 8. Discriminated unions for state management type LoadingState = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: User } | { status: 'error'; error: string }; ## TypeScript Career Opportunities India 2026 TypeScript demand consistently badh rahi hai: - Frontend roles: React, Angular, Vue with TypeScript - Backend: Node.js, NestJS, Express with TypeScript - Full-stack: Next.js, Remix with TypeScript Salary range: - Fresher: 4-8 LPA - Mid-level (2-4 years): 10-20 LPA - Senior (5+ years): 20-40 LPA ## Cyber Defence TypeScript Course Cyber Defence mein TypeScript ka complete course available hai jo JavaScript developers ko TypeScript experts banata hai. Course covers modern TypeScript patterns, React integration, aur real-world projects. ## FAQs ### Kya TypeScript seekhne ke liye JavaScript aana chahiye? Haan, JavaScript ki solid understanding zaroori hai. TypeScript basic JavaScript par built hai. ### TypeScript performance ko affect karta hai? Nahin. TypeScript browser mein directly nahi chalata. JS mein compile hota hai, toh runtime performance same rehti hai. ### Kya TypeScript code ko slower banata hai? Nahin. TypeScript compile time tool hai. Final output pure JavaScript hai jo browser execute karta hai. ### React with TypeScript best practice hai? Haan, modern React development TypeScript ke saath highly recommended hai. Better type safety aur developer experience deta hai.

Talk to a Cyber Defence Expert

Get a free consultation on cybersecurity, training and certifications. Our team responds within 10 minutes during business hours.