Skip to content

TypeScript Cheat Sheet – Complete Guide in Hindi

Updated 20 Oct 2026 8 min scan

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:

Code
let age = 25;

age = "twenty-five";

JavaScript में इस तरह का reassignment valid है। लेकिन अगर application के logic के अनुसार age हमेशा number होना चाहिए, तो यह mistake बन सकती है।

TypeScript में:

Code
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 में अंतर

FeatureJavaScriptTypeScript
Static type checkingBuilt-in नहींउपलब्ध
Type annotationsStandard syntax में नहींउपलब्ध
Browser में executionDirectly 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 देखें:

Code
TypeScript Source Code
        |
        v
Type Checking
        |
        v
JavaScript Output
        |
        v
Browser or JavaScript Runtime

Example:

Code
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 में चलाएँ:

Code
node -v
npm -v

अगर versions दिखाई देते हैं, तो आप आगे बढ़ सकते हैं।

Step 2: Project बनाएँ

एक नया folder बनाएँ और उसमें जाएँ:

Code
mkdir typescript-demo
cd typescript-demo
npm init -y

Step 3: TypeScript install करें

Code
npm install -D typescript

यह TypeScript को project की development dependency के रूप में install करता है।

Step 4: TypeScript configuration बनाएँ

Code
npx tsc --init

यह सामान्यतः project में tsconfig.json generate करता है।

Step 5: TypeScript file बनाएँ

src folder बनाएँ और src/index.ts file में लिखें:

Code
const message: string = "Hello TypeScript";

console.log(message);

Step 6: TypeScript compile करें

Code
npx tsc src/index.ts --outDir dist

Generated JavaScript file dist/index.js में मिलेगी।

इसे run करने के लिए:

Code
node dist/index.js

Expected output:

Code
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 इस तरह हो सकती है:

Code
typescript-demo/
├── node_modules/
├── src/
│   └── index.ts
├── dist/
│   └── index.js
├── package.json
├── package-lock.json
└── tsconfig.json
File / DirectoryPurpose
src/Source code रखने के लिए
index.tsMain TypeScript file
dist/Generated JavaScript output
node_modules/Installed dependencies
package.jsonProject metadata और scripts
package-lock.jsonResolved npm dependency versions
tsconfig.jsonTypeScript 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 करें।

Code
let userName: string = "Rahul";
let city: string = "Chandigarh";

Number

Integer और decimal numbers के लिए number use होता है।

Code
let age: number = 25;
let price: number = 499.99;

JavaScript में अलग-अलग integer और floating-point TypeScript types नहीं होते।

Boolean

True या false values के लिए:

Code
let isLoggedIn: boolean = true;
let isPublished: boolean = false;

Array

एक ही type की values के लिए:

Code
let scores: number[] = [80, 90, 95];

let names: string[] = ["Aman", "Riya", "Karan"];

Generic syntax भी use कर सकते हैं:

Code
let scores: Array<number> = [80, 90, 95];

Tuple

Tuple में elements की positions के अनुसार types define किए जा सकते हैं।

Code
let user: [number, string] = [1, "Aman"];

यहाँ पहला element number और दूसरा string है।

Null और Undefined

Code
let emptyValue: null = null;
let missingValue: undefined = undefined;

Strict TypeScript projects में null और undefined को handle करने के लिए appropriate types और checks जरूरी होते हैं।

Object

Code
let product: {
  name: string;
  price: number;
} = {
  name: "Laptop",
  price: 50000
};

Type Inference

हर variable में type लिखना जरूरी नहीं है।

Code
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 कर देता है।

Code
let data: any = 100;

data = "Hello";
data = true;

data.toUpperCase();

ऊपर के example में आखिरी operation runtime पर error दे सकता है, क्योंकि उस समय data boolean है।

any का बहुत ज्यादा use TypeScript के benefits कम कर सकता है।

unknown

जब data का type पता नहीं हो, तो unknown अधिक सुरक्षित विकल्प है।

Code
let data: unknown = "Hello";

if (typeof data === "string") {
  console.log(data.toUpperCase());
}

unknown value पर operation करने से पहले आपको उसका type check करना होता है।

void

ऐसे functions के लिए जिनका उपयोगी return value नहीं होता, void इस्तेमाल किया जा सकता है।

Code
function showMessage(): void {
  console.log("Welcome!");
}

Quick Comparison

TypeMeaningCommon Use
anyType checking को bypass करता हैLegacy या temporary migration
unknownValue का type अभी ज्ञात नहींExternal या untrusted data
voidFunction का उपयोगी return value नहींLogging, notifications

याद रखने वाली बात: any से बचें, unknown को check करके use करें और void को functions के return type के रूप में समझें।

7. Type Annotation और Type Inference#

Type Annotation

जब आप खुद type लिखते हैं, तो इसे type annotation कहते हैं।

Code
let userName: string = "Aman";

function add(a: number, b: number): number {
  return a + b;
}

Type Inference

जब TypeScript code से type समझ लेता है:

Code
let userName = "Aman";

function add(a: number, b: number) {
  return a + b;
}

TypeScript userName को string और add() के return को number infer कर सकता है।

Function Parameters पर ध्यान दें

Code
function greet(name: string) {
  return `Hello, ${name}`;
}

greet("Aman");
greet(100); // Type error

Function parameter पर type देने से गलत arguments पकड़ने में मदद मिलती है।

8. TypeScript Functions#

Functions के parameters और return values के types define किए जा सकते हैं।

Basic Function

Code
function multiply(a: number, b: number): number {
  return a * b;
}

console.log(multiply(5, 3));

Output:

Code
15

Optional Parameter

Parameter के बाद ? लगाने पर वह optional हो जाता है।

Code
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

Code
function greet(name: string = "Guest"): string {
  return `Hello, ${name}`;
}

greet();
greet("Aman");

Arrow Function

Code
const subtract = (a: number, b: number): number => {
  return a - b;
};

Function Type

Code
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

Code
let user: {
  id: number;
  name: string;
  email: string;
} = {
  id: 1,
  name: "Aman",
  email: "aman@example.com"
};

हर बार पूरा structure लिखना inconvenient हो सकता है। इसके लिए type या interface use कर सकते हैं।

type Alias

Code
type User = {
  id: number;
  name: string;
  email: string;
};

const user: User = {
  id: 1,
  name: "Aman",
  email: "aman@example.com"
};

interface

Code
interface Product {
  id: number;
  name: string;
  price: number;
}

const product: Product = {
  id: 101,
  name: "Keyboard",
  price: 1200
};

Optional Properties

Code
interface User {
  id: number;
  name: string;
  phone?: string;
}

phone? का अर्थ है कि phone property देना जरूरी नहीं है।

Readonly Properties

Code
interface User {
  readonly id: number;
  name: string;
}

const user: User = {
  id: 1,
  name: "Aman"
};

user.name = "Rahul"; // Valid
// user.id = 2;      // Type error

readonly TypeScript के type checking में reassignment को रोकता है। यह अपने आप runtime पर object को immutable नहीं बनाता।

type और interface में अंतर

Featuretypeinterface
Object shape define करनाहाँहाँ
Union typesहाँDirectly नहीं
Primitive aliasesहाँनहीं
ExtensionIntersection (&) या अन्य type operationsextends
Declaration mergingसामान्यतः नहींSupported
सामान्य उपयोगAliases, unions और complex typesObject contracts और extensible shapes

Example:

Code
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 होता है।

Code
let userId: string | number;

userId = 101;
userId = "USR-101";

Function में Union Type

Code
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 कर सकते हैं।

Code
type Status = "pending" | "success" | "failed";

let paymentStatus: Status = "pending";

paymentStatus = "success";
// paymentStatus = "completed"; // Type error

Practical Example: Order Status

Code
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

Code
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()

Code
function printItems(items: string | string[]): void {
  if (Array.isArray(items)) {
    items.forEach((item) => console.log(item));
  } else {
    console.log(items);
  }
}

in Operator

Code
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 कर सकता है।

Code
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

Code
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

Code
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 हो सकती है:

Code
interface User {
  profile?: {
    city?: string;
  };
}

const user: User = {};

console.log(user.profile?.city);

यहाँ optional chaining error आने से बचाती है जब profile मौजूद न हो।

Nullish Coalescing

Code
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

Code
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

Code
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;
  }
}
ModifierMeaning
publicजहाँ access allowed हो, वहाँ accessible
privateClass के अंदर access
protectedClass और उसके subclasses के अंदर access

TypeScript का private सामान्यतः compile-time restriction है। JavaScript के runtime private fields के लिए #field syntax एक अलग विकल्प है।

implements

Code
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

Code
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 कर सकता है:

Code
const numberValue = identity(100);
const stringValue = identity("Hello");

Generic Array Function

Code
function getFirstItem<T>(items: T[]): T | undefined {
  return items[0];
}

const firstNumber = getFirstItem([10, 20, 30]);
const firstName = getFirstItem(["Aman", "Riya"]);

Generic Interface

Code
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 कर सकते हैं।

Code
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 करने का एक तरीका हैं।

Code
enum Direction {
  Up,
  Down,
  Left,
  Right
}

const direction: Direction = Direction.Up;

Numeric enum की values default रूप से zero से शुरू होती हैं।

String enum का example:

Code
enum OrderStatus {
  Pending = "PENDING",
  Shipped = "SHIPPED",
  Delivered = "DELIVERED"
}

कुछ situations में literal union type अधिक simple विकल्प हो सकता है:

Code
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 है:

Code
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

Partial<T>

सभी properties optional कर देता है।

Code
type UserUpdate = Partial<User>;

const update: UserUpdate = {
  name: "Rahul"
};

यह updates या PATCH payloads के लिए उपयोगी है।

Required<T>

सभी properties को required बनाता है।

Code
interface Profile {
  name?: string;
  city?: string;
}

type CompleteProfile = Required<Profile>;

Pick<T, K>

केवल selected properties रखता है।

Code
type UserSummary = Pick<User, "id" | "name">;

Omit<T, K>

Selected properties हटा देता है।

Code
type PublicUser = Omit<User, "password">;

ध्यान दें: यह compile-time type transformation है। यह runtime object से password property को अपने आप delete नहीं करता।

Record<K, T>

Keys और values के लिए consistent type define करता है।

Code
type Role = "admin" | "editor" | "viewer";

const permissions: Record<Role, boolean> = {
  admin: true,
  editor: true,
  viewer: false
};

Readonly<T>

Properties को type checking के दौरान readonly बनाता है।

Code
type ReadonlyUser = Readonly<User>;

ReturnType<T>

Function के return type को निकालता है।

Code
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:

Code
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

index.ts:

Code
import { add, PI } from "./math";

console.log(add(5, 3));
console.log(PI);

Default Export

user.ts:

Code
export default interface User {
  id: number;
  name: string;
}

app.ts:

Code
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:

Code
{
  "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

OptionPurpose
targetOutput JavaScript का language target
moduleModule code के लिए compiler setting
moduleResolutionImports resolve करने का तरीका
strictकई strict type-checking checks enable करता है
noEmitCompiler को output files generate न करने के लिए कहता है
skipLibCheckDeclaration files की checking को skip करता है
includeकिन files को project में शामिल करना है
outDirGenerated files का output directory
rootDirSource files की expected root directory

strict: true क्यों जरूरी है?

Strict mode कई संभावित type errors को पकड़ने में मदद करता है। उदाहरण के लिए, strictNullChecks null और undefined handling को अधिक स्पष्ट बनाता है।

Code
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 में चलाएँ:

Code
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

यह Vite का React + TypeScript template बनाता है।

Common File Extensions

ExtensionPurpose
.tsTypeScript code
.tsxTypeScript + JSX
.jsJavaScript
.jsxJavaScript + JSX

React component में JSX लिखना हो, तो सामान्यतः .tsx extension use करें।

Simple TypeScript Example

src/utils.ts:

Code
export function add(a: number, b: number): number {
  return a + b;
}

src/App.tsx:

Code
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 है:

Code
npx tsc --noEmit

यह project configuration के अनुसार type checking करता है और JavaScript output emit नहीं करता।

आप इसे package.json में script के रूप में भी रख सकते हैं:

Code
{
  "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

Code
interface ButtonProps {
  title: string;
  disabled?: boolean;
}

function CustomButton({ title, disabled = false }: ButtonProps) {
  return (
    <button disabled={disabled}>
      {title}
    </button>
  );
}

export default CustomButton;

Use:

Code
<CustomButton title="Save" />
<CustomButton title="Submit" disabled />

अगर आप required title prop नहीं देंगे, तो TypeScript type error दिखाएगा।

Props में Children

Code
import type { ReactNode } from "react";

interface CardProps {
  title: string;
  children: ReactNode;
}

function Card({ title, children }: CardProps) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  );
}

Use:

Code
<Card title="Profile">
  <p>Welcome to your profile.</p>
</Card>

ReactNode कई तरह के renderable React children को represent करता है।

API Response Type

Code
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

Code
let age: number = 25;

age = "25";

Problem: String assign की जा रही है जबकि variable का type number है।

Fix: सही type की value दें या requirement के अनुसार type define करें।

Code
let age: number = 25;
age = Number("25");

Error 2: Object Property Missing

Code
interface User {
  id: number;
  name: string;
}

const user: User = {
  id: 1
};

Problem: Required name property missing है।

Fix:

Code
const user: User = {
  id: 1,
  name: "Aman"
};

Error 3: Object में Extra Property

Code
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 करें।

Code
interface User {
  id: number;
  name: string;
  age: number;
}

Error 4: Possibly Undefined

Code
const names = ["Aman", "Riya"];

const firstName = names.find((name) => name === "Karan");

console.log(firstName.toUpperCase());

Problem: find() का result undefined हो सकता है।

Fix:

Code
if (firstName !== undefined) {
  console.log(firstName.toUpperCase());
}

Error 5: any का ज्यादा उपयोग

Code
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:

Code
npx tsc --noEmit

अपने build pipeline में type checking को शामिल करें।

22. TypeScript Best Practices#

  1. Strict mode use करें: नए projects में strict: true से शुरुआत करना उपयोगी है।
  2. any कम use करें: Specific types या unknown को प्राथमिकता दें।
  3. Types को reusable बनाएँ: Common data structures के लिए type या interface define करें।
  4. Function contracts स्पष्ट रखें: Parameters और return values के types समझदारी से लिखें।
  5. Null और undefined handle करें: Optional data को बिना check किए access न करें।
  6. API data validate करें: Type annotations runtime validation का replacement नहीं हैं।
  7. Utility types use करें: Pick, Omit, Partial और Record से duplicate type definitions कम हो सकती हैं।
  8. Type assertions से सावधान रहें: as SomeType compiler को विश्वास दिलाता है; यह data को convert या validate नहीं करता।
  9. Build में type checking रखें: केवल development server के successful चलने पर निर्भर न रहें।
  10. Team conventions follow करें: Naming, file structure और type बनाम interface के लिए consistent approach रखें।
  11. Types को unnecessarily complex न बनाएँ: Readable code भी maintainability का महत्वपूर्ण हिस्सा है।
  12. Compiler configuration समझें: Browser, bundler और Node.js environments के लिए सही module settings चुनें।

23. TypeScript और JavaScript: कब क्या चुनें?#

SituationSuggested Approach
छोटा learning exampleJavaScript या TypeScript
Existing JavaScript projectGradually TypeScript adopt कर सकते हैं
बड़ा React applicationTypeScript उपयोगी हो सकता है
Shared APIs और complex data modelsTypeScript से contracts स्पष्ट हो सकते हैं
बहुत छोटा scriptJavaScript पर्याप्त हो सकता है
Team-based production projectTeam skills और requirements के अनुसार निर्णय लें

TypeScript हर project के लिए अनिवार्य नहीं है। इसका फायदा तब अधिक मिलता है जब type checking, maintainability और code contracts आपकी जरूरतों से मेल खाते हों।

24. TypeScript Quick Reference#

SyntaxMeaning
let age: number = 25Number variable
let name: string = "Aman"String variable
let active: boolean = trueBoolean variable
number[]Number array
string | numberUnion type
type ID = string | numberType alias
interface User {}Object contract
name?: stringOptional property
readonly id: numberReadonly property
function add(a: number, b: number): numberTyped function
unknownUnknown type, check before use
anyBypasses many type checks
voidNo 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 TypeType assertion, not validation
npx tsc --noEmitType-check without emitting output
npx tsc --initGenerate 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 — number
  • name — string
  • email — string
  • phone — 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 में .tsx files

Suggested learning order:

  1. JavaScript Cheat Sheet
  2. JSON Cheat Sheet
  3. Fetch / REST APIs Cheat Sheet
  4. Build Tools (Vite) Cheat Sheet
  5. TypeScript Cheat Sheet — यह article
  6. React Cheat Sheet — अगला topic