← Back to TypeScript Course | Chapter 23: Performance and Best Practices | Lesson 3 of 7

Type Narrowing के Best Practices

Type narrowing TypeScript को runtime checks के आधार पर एक broad type को एक ज़्यादा specific type में refine करने देता है। Good narrowing code clear guards उपयोग करता है और जब भी possible हो unsafe assertions avoid करता है।

Early Narrow करें

एक function के अंदर invalid या unsupported cases को जितनी जल्दी possible हो check करें — early narrowing nesting घटाता है और function की बाकी logic को एक already-validated, simpler type पर operate करते रखता है।

उदाहरण: Narrow Early

typescript
function process(value: string | null) {
  if (value === null) return;
  console.log(value.toUpperCase());
}
process("hello");

Built-in Guards उपयोग करें

जहां भी apply हो custom logic के बजाय typeof, instanceof, Array.isArray, और in operator जैसे standard runtime checks को prefer करें — TypeScript इन सभी को natively समझता है और वे दूसरे readers को intent clearly communicate करते हैं।

उदाहरण: Use Built-in Guards

typescript
function describe(value: string | number | string[]) {
  if (Array.isArray(value)) return "array";
  if (typeof value === "string") return "string";
  return "number";
}
console.log(describe([1, 2]));

Discriminants उपयोग करें

related object variants की एक family के लिए, kind या status जैसी एक shared literal discriminant property add करें — उस एक property को check करना TypeScript को एक union में correct variant select करने का एक पूरी तरह reliable तरीका देता है।

उदाहरण: Use Discriminants

typescript
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
function area(shape: Shape) {
  return shape.kind === "circle" ? Math.PI * shape.radius ** 2 : shape.side ** 2;
}
console.log(area({ kind: "square", side: 4 }));

Custom Type Guards लिखें

जब built-in guards genuinely काफी न हों, एक custom function लिखें जो value is User जैसा एक type predicate return करे — इन checks को scrupulously accurate रखें, क्योंकि TypeScript predicate जो भी claim करता है उसे आगे verify किए बिना trust करता है।

उदाहरण: Write Custom Type Guards

typescript
interface User { name: string; }
function isUser(value: unknown): value is User {
  return typeof (value as User)?.name === "string";
}
const data: unknown = { name: "Ravi" };
if (isUser(data)) console.log(data.name);

Unnecessary Assertions Avoid करें

सिर्फ एक error silence करने के लिए एक type assertion की ओर पहुंचने से बचें — एक assertion compiler को बिना किसी runtime check के आप पर trust करने के लिए कहता है, इसलिए जब भी value users, APIs, storage, या किसी और untrusted source से आए तो एक असली guard prefer करें।

उदाहरण: Avoid Unnecessary Assertions

typescript
function getLength(value: unknown): number {
  if (typeof value === "string") return value.length;
  return 0;
}
console.log(getLength("hello"));
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Early return करने के बजाय बड़े if/else blocks nest करना, जो narrowed code को पढ़ना मुश्किल बनाता है।
  2. किसी ऐसी चीज़ के लिए एक custom type guard लिखना जो typeof या instanceof पहले से check कर सकता था।
  3. Narrowing के लिए typeof x === "object" उपयोग करना और यह भूल जाना कि null भी "object" है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.