← Back to TypeScript Course | Chapter 5: Type Aliases and Union Types | Lesson 6 of 9

Type का Narrowing

Type narrowing वह process है जिसमें एक broad type को runtime checks के आधार पर एक ज़्यादा specific type में reduce किया जाता है। TypeScript कई common checks को समझता है और उनका उपयोग safer property और method access प्रदान करने के लिए करता है।
Syntax
typescript
function name(param: type1 | type2) {
  if (condition) {
    // narrowed to one type
  } else {
    // narrowed to the other
  }
}

typeof से Narrowing

typeof operator JavaScript के primitive types के बीच फर्क कर सकता है, जिनमें string, number, boolean, bigint, symbol, undefined, और function शामिल हैं।

TypeScript इन checks को specifically पहचानता है और इनका उपयोग एक union type को सिर्फ matching branch तक narrow करने के लिए करता है।

उदाहरण: Narrowing with typeof

typescript
function describe(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}
describe(3.14159);

Equality Checks से Narrowing

=== और !== जैसे equality checks literal unions और उन values दोनों को narrow कर सकते हैं जो null या undefined हो सकती हैं, एक specific value के खिलाफ सीधे compare करके।

TypeScript हर comparison के बाद exactly track करता है कि कौन सी possibilities बची हैं और type को accordingly adjust करता है।

उदाहरण: Narrowing with Equality Checks

typescript
function greet(name: string | null) {
  if (name !== null) {
    console.log(`Hello, ${name}`);
  } else {
    console.log("Hello, guest");
  }
}
greet(null);

Truthiness से Narrowing

TypeScript एक plain conditional के अंदर value कैसे उपयोग होती है इसके आधार पर भी एक type narrow कर सकता है, क्योंकि एक truthiness check naturally falsy possibilities जैसे null, undefined, false, zero, और empty strings को exclude करता है, depending on कि original type ने क्या allow किया था।

यह बिना किसी explicit typeof या equality check के भी काम करता है।

उदाहरण: Narrowing with Truthiness

typescript
function printLength(value: string | null | undefined) {
  if (value) {
    console.log(value.length);
  } else {
    console.log("No value");
  }
}
printLength("hello");

Object Unions को Narrow करना

Object unions को narrow किया जा सकता है या तो एक property check करके जो सिर्फ कुछ members के पास हो, in operator उपयोग करके, या सभी members द्वारा shared एक dedicated discriminant property के through।

Narrow करने के बाद, TypeScript उन properties तक access की permission देता है जो specifically उस member की हैं जो select हुआ था।

उदाहरण: Narrowing Object Unions

typescript
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(pet: Cat | Dog) {
  if ("meow" in pet) {
    pet.meow();
  } else {
    pet.bark();
  }
}
speak({ bark: () => console.log("Woof") });

Custom Type Predicates से Narrowing

एक custom type predicate एक function है जो आप खुद लिखते हैं जो TypeScript को exactly बताता है कि एक value को कैसे narrow करना है, special form value is Type वाले एक return type का उपयोग करते हुए।

यह आपको एक single inline typeof या equality check से ज़्यादा complex या reusable narrowing logic package करने देता है।

उदाहरण: Narrowing with Custom Type Predicates

typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}
function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim();
  } else {
    pet.fly();
  }
}
move({ swim: () => console.log("Swimming") });
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. value.toUpperCase() को एक string | number पर check करने से पहले call करना, जब TypeScript type narrow होने तक सिर्फ हर union member में common members ही allow करता है।
  2. यह भूल जाना कि narrowing सिर्फ checked block के अंदर ही रहती है, इसलिए if के बाद (इसके बाहर) variable को string के रूप में उपयोग करना वापस union type देता है।
  3. null को exclude करने के लिए if (name) check करना जब "" या 0 भी valid values हों, क्योंकि एक truthiness check उन्हें भी हटा देता है।
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 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.