JavaScript से आप interactive websites और web applications बना सकते हैं। लेकिन जैसे-जैसे project बड़ा होता है, वैसे-वैसे गलत data types, missing properties और गलत function arguments जैसी समस्याएँ ढूँढना मुश्किल हो सकता है।
TypeScript, JavaScript में static type checking जोड़ता है, जिससे code run करने से पहले कई संभावित mistakes पकड़ी जा सकती हैं। यह खासकर बड़े projects, React applications और team development में उपयोगी है।
इस TypeScript Cheat Sheet में आप सीखेंगे कि TypeScript क्या है, इसे कैसे install करें, variables और functions के types कैसे define करें, type और interface में क्या अंतर है, generics कैसे काम करते हैं और TypeScript को Vite तथा React projects में कैसे use किया जाता है।
1. TypeScript क्या है?#
TypeScript, JavaScript का एक superset है, जो JavaScript syntax के साथ static types और अतिरिक्त type-system features प्रदान करता है।
Simple words में, TypeScript आपको यह बताने में मदद करता है कि किसी variable में किस तरह का data होना चाहिए और किसी function को किस प्रकार के arguments मिलने चाहिए।
Example:
let age = 25;
age = "twenty-five";JavaScript में इस तरह का reassignment valid है। लेकिन अगर application के logic के अनुसार age हमेशा number होना चाहिए, तो यह mistake बन सकती है।
TypeScript में:
let age: number = 25;
age = "twenty-five"; // Type errorअब TypeScript editor या compiler आपको बताता है कि string को number variable में assign नहीं किया जा सकता।
याद रखें: TypeScript type checking करता है, लेकिन यह अपने आप application के सभी runtime errors को नहीं रोकता।
TypeScript क्यों जरूरी है?
- Code में type-related mistakes जल्दी पकड़ने के लिए।
- Functions और APIs का expected data स्पष्ट करने के लिए।
- IDE में autocomplete और code navigation बेहतर बनाने के लिए।
- बड़े projects को maintain करना आसान बनाने के लिए।
- Team members के बीच code contracts स्पष्ट रखने के लिए।
- Refactoring के दौरान संभावित breaking changes पहचानने के लिए।
TypeScript और JavaScript में अंतर
| Feature | JavaScript | TypeScript |
|---|---|---|
| Static type checking | Built-in नहीं | उपलब्ध |
| Type annotations | Standard syntax में नहीं | उपलब्ध |
| Browser में execution | Directly supported | आमतौर पर JavaScript में transform करना पड़ता है |
| Development autocomplete | उपलब्ध | Types की मदद से बेहतर हो सकता है |
| Type-related errors | कई errors runtime पर सामने आ सकते हैं | कई errors पहले पकड़े जा सकते हैं |
| File extension | .js | .ts |
| React components | .jsx | .tsx |
TypeScript code आमतौर पर JavaScript में compile या transpile किया जाता है। Browser सामान्यतः TypeScript type annotations को सीधे execute नहीं करता।
Official documentation: TypeScript Handbook
2. TypeScript कैसे काम करता है?#
TypeScript को समझने के लिए यह simplified workflow देखें:
TypeScript Source Code
|
v
Type Checking
|
v
JavaScript Output
|
v
Browser or JavaScript RuntimeExample:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Developer"));TypeScript compiler इस code में types check कर सकता है और compatible configuration के अनुसार JavaScript output generate कर सकता है।
ध्यान दें कि type checking और JavaScript execution अलग चीजें हैं। tsc के साथ compilation errors आने पर भी default configuration में JavaScript output emit हो सकता है। अगर errors होने पर output रोकना है, तो noEmitOnError जैसे compiler options configure किए जा सकते हैं।
TypeScript की important बात
TypeScript के types अधिकतर compile time पर काम करते हैं। ये अपने आप runtime पर incoming API data validate नहीं करते।
उदाहरण के लिए, API से गलत data आने पर केवल TypeScript interface बना देने से उस data की runtime validation नहीं होगी।
3. TypeScript कैसे install करें?#
TypeScript use करने के लिए आपके system में Node.js और npm installed होने चाहिए।
Step 1: Node.js और npm check करें
Terminal में चलाएँ:
node -v
npm -vअगर versions दिखाई देते हैं, तो आप आगे बढ़ सकते हैं।
Step 2: Project बनाएँ
एक नया folder बनाएँ और उसमें जाएँ:
mkdir typescript-demo
cd typescript-demo
npm init -yStep 3: TypeScript install करें
npm install -D typescriptयह TypeScript को project की development dependency के रूप में install करता है।
Step 4: TypeScript configuration बनाएँ
npx tsc --initयह सामान्यतः project में tsconfig.json generate करता है।
Step 5: TypeScript file बनाएँ
src folder बनाएँ और src/index.ts file में लिखें:
const message: string = "Hello TypeScript";
console.log(message);Step 6: TypeScript compile करें
npx tsc src/index.ts --outDir distGenerated JavaScript file dist/index.js में मिलेगी।
इसे run करने के लिए:
node dist/index.jsExpected output:
Hello TypeScriptध्यान दें: जब आप command में सीधे input file देते हैं, तो TypeScript compiler tsconfig.json को उसी तरह project configuration के रूप में load नहीं करता जैसे बिना input files के tsc चलाने पर करता है। Project configuration के साथ compile करने के लिए npx tsc या npx tsc -p . use करें।
Official guide: What is tsconfig.json?
4. TypeScript Project Structure#
एक simple TypeScript project की structure इस तरह हो सकती है:
typescript-demo/
├── node_modules/
├── src/
│ └── index.ts
├── dist/
│ └── index.js
├── package.json
├── package-lock.json
└── tsconfig.json| File / Directory | Purpose |
|---|---|
src/ | Source code रखने के लिए |
index.ts | Main TypeScript file |
dist/ | Generated JavaScript output |
node_modules/ | Installed dependencies |
package.json | Project metadata और scripts |
package-lock.json | Resolved npm dependency versions |
tsconfig.json | TypeScript compiler configuration |
यह एक basic example है। Real-world project में folders और files project की जरूरतों के अनुसार अलग हो सकते हैं।
5. TypeScript के Basic Data Types#
TypeScript में variables के types explicitly define किए जा सकते हैं। कई मामलों में TypeScript initial value से type infer भी कर सकता है।
String
Text data के लिए string use करें।
let userName: string = "Rahul";
let city: string = "Chandigarh";Number
Integer और decimal numbers के लिए number use होता है।
let age: number = 25;
let price: number = 499.99;JavaScript में अलग-अलग integer और floating-point TypeScript types नहीं होते।
Boolean
True या false values के लिए:
let isLoggedIn: boolean = true;
let isPublished: boolean = false;Array
एक ही type की values के लिए:
let scores: number[] = [80, 90, 95];
let names: string[] = ["Aman", "Riya", "Karan"];Generic syntax भी use कर सकते हैं:
let scores: Array<number> = [80, 90, 95];Tuple
Tuple में elements की positions के अनुसार types define किए जा सकते हैं।
let user: [number, string] = [1, "Aman"];यहाँ पहला element number और दूसरा string है।
Null और Undefined
let emptyValue: null = null;
let missingValue: undefined = undefined;Strict TypeScript projects में null और undefined को handle करने के लिए appropriate types और checks जरूरी होते हैं।
Object
let product: {
name: string;
price: number;
} = {
name: "Laptop",
price: 50000
};Type Inference
हर variable में type लिखना जरूरी नहीं है।
let courseName = "TypeScript";
let totalStudents = 100;
let isActive = true;TypeScript initial values के आधार पर types infer करता है।
Best practice: जहाँ type स्पष्ट है, वहाँ inference का उपयोग करें। जहाँ data structure या function contract को स्पष्ट करना जरूरी है, वहाँ explicit types लिखें।
6. any, unknown और void#
ये तीनों अलग-अलग situations में उपयोगी हैं।
any
any TypeScript की type checking को उस value के लिए काफी हद तक disable कर देता है।
let data: any = 100;
data = "Hello";
data = true;
data.toUpperCase();ऊपर के example में आखिरी operation runtime पर error दे सकता है, क्योंकि उस समय data boolean है।
any का बहुत ज्यादा use TypeScript के benefits कम कर सकता है।
unknown
जब data का type पता नहीं हो, तो unknown अधिक सुरक्षित विकल्प है।
let data: unknown = "Hello";
if (typeof data === "string") {
console.log(data.toUpperCase());
}unknown value पर operation करने से पहले आपको उसका type check करना होता है।
void
ऐसे functions के लिए जिनका उपयोगी return value नहीं होता, void इस्तेमाल किया जा सकता है।
function showMessage(): void {
console.log("Welcome!");
}Quick Comparison
| Type | Meaning | Common Use |
|---|---|---|
any | Type checking को bypass करता है | Legacy या temporary migration |
unknown | Value का type अभी ज्ञात नहीं | External या untrusted data |
void | Function का उपयोगी return value नहीं | Logging, notifications |
याद रखने वाली बात: any से बचें, unknown को check करके use करें और void को functions के return type के रूप में समझें।
7. Type Annotation और Type Inference#
Type Annotation
जब आप खुद type लिखते हैं, तो इसे type annotation कहते हैं।
let userName: string = "Aman";
function add(a: number, b: number): number {
return a + b;
}Type Inference
जब TypeScript code से type समझ लेता है:
let userName = "Aman";
function add(a: number, b: number) {
return a + b;
}TypeScript userName को string और add() के return को number infer कर सकता है।
Function Parameters पर ध्यान दें
function greet(name: string) {
return `Hello, ${name}`;
}
greet("Aman");
greet(100); // Type errorFunction parameter पर type देने से गलत arguments पकड़ने में मदद मिलती है।
8. TypeScript Functions#
Functions के parameters और return values के types define किए जा सकते हैं।
Basic Function
function multiply(a: number, b: number): number {
return a * b;
}
console.log(multiply(5, 3));Output:
15Optional Parameter
Parameter के बाद ? लगाने पर वह optional हो जाता है।
function greet(name: string, city?: string): string {
if (city) {
return `Hello ${name} from ${city}`;
}
return `Hello ${name}`;
}
greet("Aman");
greet("Aman", "Chandigarh");Optional parameters को required parameters के बाद रखें।
Default Parameter
function greet(name: string = "Guest"): string {
return `Hello, ${name}`;
}
greet();
greet("Aman");Arrow Function
const subtract = (a: number, b: number): number => {
return a - b;
};Function Type
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;इससे कई functions के लिए एक consistent signature define किया जा सकता है।
9. Object Types, type और interface#
Applications में users, products, orders और API responses जैसे objects का structure define करना बहुत जरूरी होता है।
Object Type
let user: {
id: number;
name: string;
email: string;
} = {
id: 1,
name: "Aman",
email: "aman@example.com"
};हर बार पूरा structure लिखना inconvenient हो सकता है। इसके लिए type या interface use कर सकते हैं।
type Alias
type User = {
id: number;
name: string;
email: string;
};
const user: User = {
id: 1,
name: "Aman",
email: "aman@example.com"
};interface
interface Product {
id: number;
name: string;
price: number;
}
const product: Product = {
id: 101,
name: "Keyboard",
price: 1200
};Optional Properties
interface User {
id: number;
name: string;
phone?: string;
}phone? का अर्थ है कि phone property देना जरूरी नहीं है।
Readonly Properties
interface User {
readonly id: number;
name: string;
}
const user: User = {
id: 1,
name: "Aman"
};
user.name = "Rahul"; // Valid
// user.id = 2; // Type errorreadonly TypeScript के type checking में reassignment को रोकता है। यह अपने आप runtime पर object को immutable नहीं बनाता।
type और interface में अंतर
| Feature | type | interface |
|---|---|---|
| Object shape define करना | हाँ | हाँ |
| Union types | हाँ | Directly नहीं |
| Primitive aliases | हाँ | नहीं |
| Extension | Intersection (&) या अन्य type operations | extends |
| Declaration merging | सामान्यतः नहीं | Supported |
| सामान्य उपयोग | Aliases, unions और complex types | Object contracts और extensible shapes |
Example:
type ID = string | number;
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
}
type Admin = Person & {
permissions: string[];
};कौन-सा use करें? Object contract के लिए interface और unions या अन्य type compositions के लिए type उपयोगी है। दोनों valid विकल्प हैं; project की consistency भी महत्वपूर्ण है।
10. Union Types और Literal Types#
Union Type
जब value एक से ज्यादा possible types में से किसी एक की हो सकती है, तब union type use होता है।
let userId: string | number;
userId = 101;
userId = "USR-101";Function में Union Type
function printId(id: string | number): void {
console.log(id);
}
printId(101);
printId("USR-101");Union type होने का मतलब यह नहीं कि हर operation दोनों types पर valid होगा।
Literal Type
किसी variable के लिए fixed values specify कर सकते हैं।
type Status = "pending" | "success" | "failed";
let paymentStatus: Status = "pending";
paymentStatus = "success";
// paymentStatus = "completed"; // Type errorPractical Example: Order Status
type OrderStatus = "pending" | "processing" | "shipped" | "delivered";
function updateOrderStatus(status: OrderStatus): void {
console.log(`Order status: ${status}`);
}
updateOrderStatus("shipped");Literal unions typo और invalid values को रोकने में मदद करते हैं।
11. Type Narrowing और Type Guards#
Union types के साथ काम करते समय TypeScript को किसी value का actual type check करके बताना पड़ सकता है।
इस process को type narrowing कहते हैं।
typeof
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}यहाँ TypeScript समझता है कि if block में value string है और दूसरे block में number है।
Array.isArray()
function printItems(items: string | string[]): void {
if (Array.isArray(items)) {
items.forEach((item) => console.log(item));
} else {
console.log(items);
}
}in Operator
type Admin = {
name: string;
permissions: string[];
};
type Customer = {
name: string;
purchaseCount: number;
};
function describeUser(user: Admin | Customer): string {
if ("permissions" in user) {
return `${user.name} is an admin`;
}
return `${user.name} is a customer`;
}Discriminated Union
जब अलग-अलग object types में एक common literal property होती है, तो TypeScript उन्हें आसानी से distinguish कर सकता है।
type SuccessResponse = {
status: "success";
data: string;
};
type ErrorResponse = {
status: "error";
message: string;
};
type ApiResponse = SuccessResponse | ErrorResponse;
function handleResponse(response: ApiResponse): string {
if (response.status === "success") {
return response.data;
}
return response.message;
}इस pattern का उपयोग API responses, authentication states और UI loading states में किया जा सकता है।
Official guide: TypeScript Narrowing
12. TypeScript Arrays और Objects#
Array of Objects
interface Product {
id: number;
name: string;
price: number;
}
const products: Product[] = [
{
id: 1,
name: "Mouse",
price: 500
},
{
id: 2,
name: "Keyboard",
price: 1200
}
];Array Methods
const productNames = products.map((product) => product.name);
const expensiveProducts = products.filter(
(product) => product.price > 1000
);
const selectedProduct = products.find(
(product) => product.id === 1
);map() transformed array देता है, filter() matching elements देता है और find() पहला matching element या undefined देता है।
Optional Chaining
अगर property missing या null हो सकती है:
interface User {
profile?: {
city?: string;
};
}
const user: User = {};
console.log(user.profile?.city);यहाँ optional chaining error आने से बचाती है जब profile मौजूद न हो।
Nullish Coalescing
const city = user.profile?.city ?? "Unknown City";?? केवल null या undefined होने पर fallback value देता है। इसके विपरीत || सभी falsy values, जैसे 0, false और empty string पर fallback कर सकता है।
13. TypeScript Classes और Access Modifiers#
TypeScript classes में properties और methods के types define कर सकते हैं।
Basic Class
class User {
name: string;
constructor(name: string) {
this.name = name;
}
greet(): string {
return `Hello, ${this.name}`;
}
}
const user = new User("Aman");
console.log(user.greet());public, private और protected
class Account {
public owner: string;
private balance: number;
protected accountType: string;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
this.accountType = "Savings";
}
getBalance(): number {
return this.balance;
}
}| Modifier | Meaning |
|---|---|
public | जहाँ access allowed हो, वहाँ accessible |
private | Class के अंदर access |
protected | Class और उसके subclasses के अंदर access |
TypeScript का private सामान्यतः compile-time restriction है। JavaScript के runtime private fields के लिए #field syntax एक अलग विकल्प है।
implements
interface Printable {
print(): void;
}
class Invoice implements Printable {
print(): void {
console.log("Printing invoice");
}
}implements class को interface के expected structure के अनुरूप बनाने में मदद करता है।
14. Generics क्या हैं?#
Generics reusable functions, interfaces और classes बनाने में मदद करते हैं, जहाँ input के type के आधार पर output का type भी preserve किया जा सकता है।
बिना Generic के
अगर function को हर type के लिए अलग बनाना पड़े, तो duplicate code बढ़ सकता है।
Generic Function
function identity<T>(value: T): T {
return value;
}
const numberValue = identity<number>(100);
const stringValue = identity<string>("Hello");यहाँ T एक type parameter है। यह कोई fixed TypeScript keyword नहीं है; आप meaningful नाम भी रख सकते हैं।
TypeScript अक्सर type खुद infer कर सकता है:
const numberValue = identity(100);
const stringValue = identity("Hello");Generic Array Function
function getFirstItem<T>(items: T[]): T | undefined {
return items[0];
}
const firstNumber = getFirstItem([10, 20, 30]);
const firstName = getFirstItem(["Aman", "Riya"]);Generic Interface
interface ApiResponse<T> {
success: boolean;
data: T;
}
interface User {
id: number;
name: string;
}
const response: ApiResponse<User> = {
success: true,
data: {
id: 1,
name: "Aman"
}
};Generic Constraint
extends के जरिए generic type की minimum requirement define कर सकते हैं।
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength("TypeScript");
getLength([1, 2, 3]);
// getLength(100); // Type errorयह function उन्हीं values को accept करता है जिनमें numeric length property मौजूद हो।
Official guide: TypeScript Generics
15. Enums और Alternatives#
Enums related named constants का group define करने का एक तरीका हैं।
enum Direction {
Up,
Down,
Left,
Right
}
const direction: Direction = Direction.Up;Numeric enum की values default रूप से zero से शुरू होती हैं।
String enum का example:
enum OrderStatus {
Pending = "PENDING",
Shipped = "SHIPPED",
Delivered = "DELIVERED"
}कुछ situations में literal union type अधिक simple विकल्प हो सकता है:
type OrderStatus = "PENDING" | "SHIPPED" | "DELIVERED";
const status: OrderStatus = "PENDING";Enums और union types एक जैसे नहीं हैं। Project की requirements, runtime behavior और team conventions के अनुसार चुनाव करें।
16. Utility Types Cheat Sheet#
TypeScript कई built-in utility types देता है, जिनकी मदद से existing types से नए types बनाए जा सकते हैं।
मान लीजिए हमारे पास यह interface है:
interface User {
id: number;
name: string;
email: string;
password: string;
}Partial<T>
सभी properties optional कर देता है।
type UserUpdate = Partial<User>;
const update: UserUpdate = {
name: "Rahul"
};यह updates या PATCH payloads के लिए उपयोगी है।
Required<T>
सभी properties को required बनाता है।
interface Profile {
name?: string;
city?: string;
}
type CompleteProfile = Required<Profile>;Pick<T, K>
केवल selected properties रखता है।
type UserSummary = Pick<User, "id" | "name">;Omit<T, K>
Selected properties हटा देता है।
type PublicUser = Omit<User, "password">;ध्यान दें: यह compile-time type transformation है। यह runtime object से password property को अपने आप delete नहीं करता।
Record<K, T>
Keys और values के लिए consistent type define करता है।
type Role = "admin" | "editor" | "viewer";
const permissions: Record<Role, boolean> = {
admin: true,
editor: true,
viewer: false
};Readonly<T>
Properties को type checking के दौरान readonly बनाता है।
type ReadonlyUser = Readonly<User>;ReturnType<T>
Function के return type को निकालता है।
function getUser() {
return {
id: 1,
name: "Aman"
};
}
type UserResult = ReturnType<typeof getUser>;Quick Reference
| Utility Type | काम |
|---|---|
Partial<T> | सभी properties optional |
Required<T> | सभी properties required |
Pick<T, K> | Selected properties |
Omit<T, K> | Selected properties हटाना |
Record<K, T> | Keys और values का mapping |
Readonly<T> | Properties readonly |
ReturnType<T> | Function return type |
Parameters<T> | Function parameter types |
NonNullable<T> | null और undefined हटाना |
Official reference: TypeScript Utility Types
17. TypeScript Modules: Import और Export#
बड़े projects में code को अलग-अलग files में रखना maintainability बेहतर करता है।
Named Export
math.ts:
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;index.ts:
import { add, PI } from "./math";
console.log(add(5, 3));
console.log(PI);Default Export
user.ts:
export default interface User {
id: number;
name: string;
}app.ts:
import type User from "./user";
const user: User = {
id: 1,
name: "Aman"
};import type का उपयोग केवल type imports के लिए किया जा सकता है। इससे code का intent स्पष्ट होता है और type-only imports को emit होने वाले JavaScript से हटाया जा सकता है।
Module resolution project के runtime या bundler के अनुसार configure होना चाहिए।
18. tsconfig.json की Important Settings#
tsconfig.json TypeScript project की compiler settings define करता है।
Example:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}यह configuration bundler-based frontend project के लिए एक illustrative example है। इसे हर Node.js project या हर runtime के लिए बिना बदलाव use नहीं करना चाहिए।
Important Options
| Option | Purpose |
|---|---|
target | Output JavaScript का language target |
module | Module code के लिए compiler setting |
moduleResolution | Imports resolve करने का तरीका |
strict | कई strict type-checking checks enable करता है |
noEmit | Compiler को output files generate न करने के लिए कहता है |
skipLibCheck | Declaration files की checking को skip करता है |
include | किन files को project में शामिल करना है |
outDir | Generated files का output directory |
rootDir | Source files की expected root directory |
strict: true क्यों जरूरी है?
Strict mode कई संभावित type errors को पकड़ने में मदद करता है। उदाहरण के लिए, strictNullChecks null और undefined handling को अधिक स्पष्ट बनाता है।
function getLength(value: string | null): number {
if (value === null) {
return 0;
}
return value.length;
}यह explicit null check code को safer और clearer बनाता है।
Official guide: TSConfig Reference
19. TypeScript और Vite Setup#
पिछले topic में आपने Vite build tool सीखा था। अब उसी ecosystem में TypeScript use करते हैं।
नया React + TypeScript Project
Terminal में चलाएँ:
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run devयह Vite का React + TypeScript template बनाता है।
Common File Extensions
| Extension | Purpose |
|---|---|
.ts | TypeScript code |
.tsx | TypeScript + JSX |
.js | JavaScript |
.jsx | JavaScript + JSX |
React component में JSX लिखना हो, तो सामान्यतः .tsx extension use करें।
Simple TypeScript Example
src/utils.ts:
export function add(a: number, b: number): number {
return a + b;
}src/App.tsx:
import { add } from "./utils";
function App() {
return (
<main>
<h1>TypeScript + React</h1>
<p>Result: {add(10, 20)}</p>
</main>
);
}
export default App;Vite development server code को browser के लिए serve करने में मदद करता है। ध्यान रखें कि Vite का fast development transform अपने आप full TypeScript type checking की guarantee नहीं देता। Type errors check करने के लिए अलग से TypeScript compiler चलाएँ।
Type Check Command
अगर project में TypeScript installed है:
npx tsc --noEmitयह project configuration के अनुसार type checking करता है और JavaScript output emit नहीं करता।
आप इसे package.json में script के रूप में भी रख सकते हैं:
{
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"typecheck": "tsc --noEmit",
"preview": "vite preview"
}
}यह script example उन Vite templates के लिए है जहाँ project references के साथ tsc -b configuration मौजूद है। अगर आपके project का tsconfig अलग है, तो build script को उसी के अनुसार adjust करें।
Reference: Vite Getting Started
20. TypeScript और React में Props कैसे Define करें?#
React में TypeScript का एक बहुत common use case component props को type करना है।
Props Interface
interface ButtonProps {
title: string;
disabled?: boolean;
}
function CustomButton({ title, disabled = false }: ButtonProps) {
return (
<button disabled={disabled}>
{title}
</button>
);
}
export default CustomButton;Use:
<CustomButton title="Save" />
<CustomButton title="Submit" disabled />अगर आप required title prop नहीं देंगे, तो TypeScript type error दिखाएगा।
Props में Children
import type { ReactNode } from "react";
interface CardProps {
title: string;
children: ReactNode;
}
function Card({ title, children }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}Use:
<Card title="Profile">
<p>Welcome to your profile.</p>
</Card>ReactNode कई तरह के renderable React children को represent करता है।
API Response Type
interface Product {
id: number;
title: string;
price: number;
}
async function fetchProducts(): Promise<Product[]> {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error("Failed to fetch products");
}
return response.json() as Promise<Product[]>;
}यहाँ return type API response के expected structure को represent करता है। लेकिन as Promise<Product[]> runtime validation नहीं करता। अगर API untrusted data भेजती है, तो उसे runtime पर validate करना चाहिए।
21. TypeScript में Common Errors और Fixes#
Error 1: Type Mismatch
let age: number = 25;
age = "25";Problem: String assign की जा रही है जबकि variable का type number है।
Fix: सही type की value दें या requirement के अनुसार type define करें।
let age: number = 25;
age = Number("25");Error 2: Object Property Missing
interface User {
id: number;
name: string;
}
const user: User = {
id: 1
};Problem: Required name property missing है।
Fix:
const user: User = {
id: 1,
name: "Aman"
};Error 3: Object में Extra Property
interface User {
id: number;
name: string;
}
const user: User = {
id: 1,
name: "Aman",
age: 25
};इस तरह के direct object literal में TypeScript excess-property error दे सकता है।
Fix: अगर age वास्तव में model का हिस्सा है, तो type में add करें।
interface User {
id: number;
name: string;
age: number;
}Error 4: Possibly Undefined
const names = ["Aman", "Riya"];
const firstName = names.find((name) => name === "Karan");
console.log(firstName.toUpperCase());Problem: find() का result undefined हो सकता है।
Fix:
if (firstName !== undefined) {
console.log(firstName.toUpperCase());
}Error 5: any का ज्यादा उपयोग
const user: any = getUserData();Problem: Type checking के benefits कम हो जाते हैं।
Fix: जहाँ संभव हो, specific type या unknown use करें और incoming data validate करें।
Error 6: TypeScript Code Run नहीं हो रहा
Problem: .ts file को सीधे ऐसे runtime में चलाने की कोशिश करना जो TypeScript support नहीं करता।
Fix: अपने project के अनुसार TypeScript compiler या compatible runtime/tooling use करें। Browser frontend project में Vite जैसे tool का उपयोग किया जा सकता है।
Error 7: Vite Build में Type Error नहीं दिख रहा
Problem: Development transform और type checking अलग processes हो सकते हैं।
Fix:
npx tsc --noEmitअपने build pipeline में type checking को शामिल करें।
22. TypeScript Best Practices#
- Strict mode use करें: नए projects में
strict: trueसे शुरुआत करना उपयोगी है। anyकम use करें: Specific types याunknownको प्राथमिकता दें।- Types को reusable बनाएँ: Common data structures के लिए
typeयाinterfacedefine करें। - Function contracts स्पष्ट रखें: Parameters और return values के types समझदारी से लिखें।
- Null और undefined handle करें: Optional data को बिना check किए access न करें।
- API data validate करें: Type annotations runtime validation का replacement नहीं हैं।
- Utility types use करें:
Pick,Omit,PartialऔरRecordसे duplicate type definitions कम हो सकती हैं। - Type assertions से सावधान रहें:
as SomeTypecompiler को विश्वास दिलाता है; यह data को convert या validate नहीं करता। - Build में type checking रखें: केवल development server के successful चलने पर निर्भर न रहें।
- Team conventions follow करें: Naming, file structure और
typeबनामinterfaceके लिए consistent approach रखें। - Types को unnecessarily complex न बनाएँ: Readable code भी maintainability का महत्वपूर्ण हिस्सा है।
- Compiler configuration समझें: Browser, bundler और Node.js environments के लिए सही module settings चुनें।
23. TypeScript और JavaScript: कब क्या चुनें?#
| Situation | Suggested Approach |
|---|---|
| छोटा learning example | JavaScript या TypeScript |
| Existing JavaScript project | Gradually TypeScript adopt कर सकते हैं |
| बड़ा React application | TypeScript उपयोगी हो सकता है |
| Shared APIs और complex data models | TypeScript से contracts स्पष्ट हो सकते हैं |
| बहुत छोटा script | JavaScript पर्याप्त हो सकता है |
| Team-based production project | Team skills और requirements के अनुसार निर्णय लें |
TypeScript हर project के लिए अनिवार्य नहीं है। इसका फायदा तब अधिक मिलता है जब type checking, maintainability और code contracts आपकी जरूरतों से मेल खाते हों।
24. TypeScript Quick Reference#
| Syntax | Meaning |
|---|---|
let age: number = 25 | Number variable |
let name: string = "Aman" | String variable |
let active: boolean = true | Boolean variable |
number[] | Number array |
string | number | Union type |
type ID = string | number | Type alias |
interface User {} | Object contract |
name?: string | Optional property |
readonly id: number | Readonly property |
function add(a: number, b: number): number | Typed function |
unknown | Unknown type, check before use |
any | Bypasses many type checks |
void | No useful return value |
Promise<string> | Promise resolving to string |
Partial<User> | All properties optional |
Pick<User, "id"> | Select a property |
Omit<User, "password"> | Remove a property from the type |
Record<string, number> | String keys mapped to numbers |
value as Type | Type assertion, not validation |
npx tsc --noEmit | Type-check without emitting output |
npx tsc --init | Generate TypeScript configuration |
25. Knowledge Check#
इन questions के answers खुद देने की कोशिश करें।
Q1. TypeScript का मुख्य purpose क्या है?
A. केवल CSS लिखना
B. JavaScript के लिए static type checking उपलब्ध कराना
C. Database create करना
D. केवल server host करना
Q2. कौन-सा type अधिक सुरक्षित तरीके से unknown data को represent करता है?
A. any
B. unknown
C. void
D. never
Q3. इनमें से कौन-सा union type है?
A. number[]
B. string | number
C. boolean
D. Promise<void>
Q4. Partial<User> क्या करता है?
A. सभी properties optional करता है
B. सभी properties delete करता है
C. Object को runtime पर freeze करता है
D. केवल एक property रखता है
Q5. Vite project में TypeScript type-checking के लिए कौन-सी command उपयोगी है?
A. npm run preview
B. npx tsc --noEmit
C. git push
D. npm cache clean
Answers: 1-B, 2-B, 3-B, 4-A, 5-B.
26. Practice Exercises#
Exercise 1: User Type बनाएँ
एक User type या interface बनाएँ, जिसमें ये properties हों:
id— numbername— stringemail— stringphone— optional string
फिर एक valid user object बनाएँ।
Exercise 2: Calculator Function
एक calculateTotal() function बनाएँ जो price और quantity दोनों number parameters ले और total number return करे।
Test करें कि string pass करने पर TypeScript क्या error दिखाता है।
Exercise 3: Product List
एक Product interface बनाएँ जिसमें id, name और price हों। कम से कम तीन products का typed array बनाएँ और ₹1,000 से महँगे products filter करें।
Exercise 4: Union Type
OrderStatus बनाएँ जिसमें "pending", "shipped" और "delivered" allowed हों। एक function बनाएँ जो status accept करे और message return करे।
Exercise 5: React Props
React + TypeScript में ProfileCard component बनाएँ। इसके props में name: string, age: number और city?: string रखें। City न मिलने पर "Not provided" दिखाएँ।
27. Summary#
इस TypeScript Cheat Sheet में आपने सीखा:
- TypeScript क्या है और JavaScript से कैसे अलग है।
- TypeScript install, configure और compile कैसे करें।
string,number,boolean, arrays और tuples।- Type inference और type annotations।
- Functions, optional parameters और return types।
type,interface, union types और literal types।- Type narrowing, classes और generics।
- Utility types और modules।
tsconfig.jsonकी important settings।- Vite और React projects में TypeScript का उपयोग।
- Common errors, best practices और quick reference।
Short में: TypeScript आपके code के expected data structures और function contracts को स्पष्ट करता है और कई mistakes को execution से पहले पकड़ने में मदद करता है। इसकी सबसे अच्छी शुरुआत basic types, functions, object types और strict type checking से होती है।
28. आगे क्या सीखें?#
आपकी JavaScript Ecosystem learning path में अगला topic है React Cheat Sheet – Complete Guide in Hindi।
React सीखते समय TypeScript की ये concepts खास तौर पर काम आएँगी:
- Component props के types
useStateऔर event handlers- API response types
- Reusable interfaces और type aliases
- React components में
.tsxfiles
Suggested learning order:
- JavaScript Cheat Sheet
- JSON Cheat Sheet
- Fetch / REST APIs Cheat Sheet
- Build Tools (Vite) Cheat Sheet
- TypeScript Cheat Sheet — यह article
- React Cheat Sheet — अगला topic