पाठ 21 / 26

डिस्क्रिमिनेटेड यूनियन

साझा लिटरल फ़ील्ड, TS को यूनियन को पूरी तरह संकरा करने देती है।

एक डिस्क्रिमिनेटेड यूनियन

हर वैरिएंट को एक साझा लिटरल फ़ील्ड (kind) दें — TS इसका उपयोग करके ठीक-ठीक जानता है कि आपके पास कौन-सा आकार है।

interface Circle {
  kind: "circle";
  radius: number;
}
interface Square {
  kind: "square";
  side: number;
}
type Shape = Circle | Square;

पूर्ण switch

kind पर switch करने से हर केस अपने-आप संकरा हो जाता है, कोई मैनुअल कास्टिंग नहीं।

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
  }
}

एग्ज़ॉस्टिवनेस जाँच

एक default: const _exhaustive: never = shape; ब्रांच जोड़ें — अगर कभी कोई नया shape वैरिएंट जोड़ा जाए और हैंडल न किया जाए, TS इसे कंपाइल-टाइम पर पकड़ लेता है।