टाइपस्क्रिप्ट आधुनिक जावास्क्रिप्ट विकास के लिए मानक बन गया है। 2026 में, 80% से अधिक नई जावास्क्रिप्ट परियोजनाएँ टाइपस्क्रिप्ट का उपयोग करती हैं। यह संपूर्ण मार्गदर्शिका बुनियादी प्रकारों से लेकर उन्नत जेनरिक, डेकोरेटर और उत्पादन पैटर्न तक सब कुछ कवर करती है।
📋 Table of Contents
2026 में टाइपस्क्रिप्ट क्यों?
जावास्क्रिप्ट की गतिशील प्रकृति रनटाइम त्रुटियों का कारण बनती है जिसे टाइपस्क्रिप्ट संकलन समय पर पकड़ लेता है। लाभ स्पष्ट हैं:
- बग्स को जल्दी पकड़ें– संकलन समय पर टाइप त्रुटियाँ, उत्पादन में नहीं
- बेहतर टूलींग– वीएस कोड में स्वत: पूर्ण, रीफैक्टरिंग और नेविगेशन
- स्व-दस्तावेजीकरण कोड– प्रकार इनलाइन दस्तावेज़ीकरण के रूप में कार्य करते हैं
- बड़े पैमाने पर आत्मविश्वास– हजारों फाइलों में सुरक्षित रीफैक्टरिंग
स्थापना और सेटअप
टाइपस्क्रिप्ट को विश्व स्तर पर या एक देव निर्भरता के रूप में स्थापित करें:
# Install TypeScript
npm install -g typescript
# Or as dev dependency
npm install --save-dev typescript
# Check version
tsc --version
# Initialize tsconfig
tsc --init
tsconfig.json सर्वोत्तम अभ्यास
एक उत्पादन के लिए तैयारtsconfig.json2026 के लिए:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"lib": ["ES2022", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
बुनियादी प्रकार
टाइपस्क्रिप्ट का प्रकार सिस्टम आदिम से शुरू होता है और बनता है:
// Primitives
const name: string = "Alice";
const age: number = 30;
const active: boolean = true;
const nothing: null = null;
const unknown: undefined = undefined;
// Arrays
const scores: number[] = [95, 87, 92];
const tags: Array<string> = ["ts", "js", "node"];
// Tuples (fixed-length arrays with known types)
const point: [number, number] = [10, 20];
const entry: [string, number] = ["age", 30];
// Union types
let id: string | number = "user_123";
id = 456; // also valid
// Literal types
type Direction = "north" | "south" | "east" | "west";
const dir: Direction = "north";
// any, unknown, never
const userInput: unknown = getUserInput();
if (typeof userInput === "string") {
console.log(userInput.toUpperCase()); // type narrowed to string
}
इंटरफ़ेस बनाम प्रकार
दोनों वस्तु आकृतियों को परिभाषित करते हैं, लेकिन मुख्य अंतरों के साथ:
// Interface — can be merged (declaration merging)
interface User {
id: number;
name: string;
email?: string; // optional
}
// Extend interface
interface AdminUser extends User {
role: "admin" | "superadmin";
permissions: string[];
}
// Type alias — more flexible, supports unions and intersections
type ApiResponse<T> = {
data: T;
error: string | null;
status: number;
};
// Intersection type
type AuthUser = User & { token: string };
// Prefer interface for object shapes, type for unions/intersections
const user: AdminUser = {
id: 1,
name: "Alice",
role: "admin",
permissions: ["read", "write"]
};
जेनेरिक्स
जेनेरिक कोड को टाइप-सुरक्षित रखते हुए पुन: प्रयोज्य बनाते हैं:
// Generic function
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const num = first([1, 2, 3]); // type: number | undefined
const str = first(["a", "b"]); // type: string | undefined
// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Alice", age: 30 };
const name = getProperty(user, "name"); // type: string
const id = getProperty(user, "id"); // type: number
// Generic interface
interface Repository<T> {
findById(id: number): Promise<T | null>;
findAll(): Promise<T[]>;
create(item: Omit<T, "id">): Promise<T>;
update(id: number, item: Partial<T>): Promise<T>;
delete(id: number): Promise<void>;
}
// Generic class
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
peek(): T | undefined { return this.items[this.items.length - 1]; }
isEmpty(): boolean { return this.items.length === 0; }
}
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
उपयोगिता प्रकार
शक्तिशाली अंतर्निहित उपयोगिता प्रकारों के साथ टाइपस्क्रिप्ट जहाज:
interface Product {
id: number;
name: string;
price: number;
description: string;
inStock: boolean;
}
// Partial — all fields optional
type ProductDraft = Partial<Product>;
// Required — all fields required
type FullProduct = Required<Product>;
// Pick — select specific fields
type ProductSummary = Pick<Product, "id" | "name" | "price">;
// Omit — exclude fields
type NewProduct = Omit<Product, "id">;
// Readonly — prevent mutation
type ImmutableProduct = Readonly<Product>;
// Record — map type
type CategoryMap = Record<string, Product[]>;
// ReturnType — extract function return type
async function fetchUser() {
return { id: 1, name: "Alice", email: "alice@example.com" };
}
type User = Awaited<ReturnType<typeof fetchUser>>;
// Parameters — extract function parameters
function createOrder(userId: number, items: string[], total: number) {}
type OrderParams = Parameters<typeof createOrder>;
उन्नत पैटर्न: सशर्त प्रकार
// Conditional type
type IsArray<T> = T extends any[] ? true : false;
type A = IsArray<string[]>; // true
type B = IsArray<string>; // false
// Infer keyword
type UnpackArray<T> = T extends (infer U)[] ? U : T;
type Unpacked = UnpackArray<string[]>; // string
type NotArray = UnpackArray<number>; // number
// Mapped types
type Optional<T> = {
[K in keyof T]?: T[K];
};
// Template literal types (TypeScript 4.1+)
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
type FocusEvent = EventName<"focus">; // "onFocus"
// Discriminated unions
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function processResult<T>(result: Result<T>): T {
if (result.success) {
return result.data; // TypeScript knows this is T
}
throw new Error(result.error); // TypeScript knows error is string
}
प्रतिक्रिया के साथ टाइपस्क्रिप्ट
import React, { useState, useCallback, FC } from "react";
interface ButtonProps {
label: string;
onClick: () => void;
variant?: "primary" | "secondary" | "danger";
disabled?: boolean;
children?: React.ReactNode;
}
const Button: FC<ButtonProps> = ({
label,
onClick,
variant = "primary",
disabled = false,
children
}) => {
return (
<button
className={`btn btn-${variant}`}
onClick={onClick}
disabled={disabled}
>
{children ?? label}
</button>
);
};
// Generic component
interface ListProps<T> {
items: T[];
renderItem: (item: T, index: number) => React.ReactNode;
keyExtractor: (item: T) => string | number;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={keyExtractor(item)}>{renderItem(item, index)}</li>
))}
</ul>
);
}
// Custom hook with types
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
const setStoredValue = useCallback((newValue: T) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
}, [key]);
return [value, setStoredValue] as const;
}
टाइपस्क्रिप्ट डेकोरेटर्स (2026)
टाइपस्क्रिप्ट 5.0+ स्टेज 3 डेकोरेटर्स का समर्थन करता है:
// Class decorator
function singleton<T extends { new(...args: any[]): {} }>(constructor: T) {
let instance: T;
return class extends constructor {
constructor(...args: any[]) {
if (instance) return instance;
super(...args);
instance = this as any;
}
};
}
// Method decorator — log execution time
function measure(_target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = async function (...args: any[]) {
const start = performance.now();
const result = await original.apply(this, args);
const duration = performance.now() - start;
console.log(`${key} took ${duration.toFixed(2)}ms`);
return result;
};
return descriptor;
}
class UserService {
@measure
async fetchUsers(): Promise<User[]> {
const r = await fetch("/api/users");
return r.json();
}
}
सख्त मोड चेकलिस्ट
अधिकतम प्रकार की सुरक्षा के लिए इन कंपाइलर विकल्पों को सक्षम करें:
strict: true– सभी सख्त जांच सक्षम बनाता हैnoUncheckedIndexedAccess: true– ऐरे एक्सेस रिटर्नT | undefinedexactOptionalPropertyTypes: true—undefinedवैकल्पिक को असाइन करने योग्य नहींnoImplicitOverride: true– प्रयोग करना चाहिएoverrideकीवर्डnoPropertyAccessFromIndexSignature: true– सूचकांक चिह्नों के लिए ब्रैकेट नोटेशन का उपयोग करें
2026 में टाइपस्क्रिप्ट टूलींग
- बायोम– सबसे तेज़ लिंटर + फ़ॉर्मेटर, टाइपस्क्रिप्ट-नेटिव
- tsx– टाइपस्क्रिप्ट फ़ाइलों को संकलित किए बिना सीधे चलाएँ
- tsup– टाइपस्क्रिप्ट लाइब्रेरीज़ के लिए शून्य-कॉन्फ़िगरेशन बंडलर
- विटेस्ट– देशी ईएसएम के साथ टाइपस्क्रिप्ट-प्रथम परीक्षण
- टीआरपीसी– फुल-स्टैक ऐप्स के लिए एंड-टू-एंड प्रकार की सुरक्षा
चाबी छीनना
2026 में टाइपस्क्रिप्ट पेशेवर जावास्क्रिप्ट विकास के लिए परिपक्व, तेज़ और आवश्यक है। के साथ शुरूstrict: true, ऑब्जेक्ट आकृतियों के लिए इंटरफेस का उपयोग करें, उपयोगिता प्रकारों पर निर्भर रहें, और पुन: प्रयोज्य कोड के लिए जेनेरिक का लाभ उठाएं। टूलींग पारिस्थितिकी तंत्र कभी भी बेहतर नहीं रहा।
🔗 Share this article
✍️ Leave a Comment