بتل کد Battle Codeدارد باز می‌شود…

جلسه‌ی 19: برچسب روی هر شکل Tagged Unions

وقتی یک چیز چند حالت دارد و هر حالت داده‌ی خودش را، به هر حالت یک برچسب kind می‌دهی. با switch روی برچسب کار می‌کنی، و never خبرت می‌کند اگر حالتی را جا انداخته باشی.

در این جلسه یاد می‌گیری

درس

علی برای یک برنامه‌ی نقاشی دو شکل دارد: دایره (با شعاع) و مستطیل (با عرض و ارتفاع). او همه را در یک شکل ریخته و فیلدها را اختیاری کرده است. حالا این هم قبول می‌شود: دایره‌ای که شعاع ندارد ولی عرض دارد! تایپ‌اسکریپت ایرادی نمی‌گیرد، چون همه‌ی فیلدها اختیاری‌اند. اجرا کن: مساحت شد 0. یک اشتباه بی‌صدای دیگر.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Shape {
  kind: string;
  radius?: number;
  width?: number;
  height?: number;
}

function area(s: Shape): number {
  if (s.kind === "circle") {
    return 3 * (s.radius ?? 0) * (s.radius ?? 0);
  }
  return (s.width ?? 0) * (s.height ?? 0);
}

const wrong: Shape = { kind: "circle", width: 5 };
show("Area: " + area(wrong));
</script>

راه بهتر: برای هر حالت یک شکل جدا بنویس، و به هر کدام یک فیلد kind با نوع دقیق بده (جلسه‌ی ۱۷). Circle همیشه kind: "circle" دارد و حتماً radius. Rect همیشه kind: "rect" دارد و حتماً width و height. بعد با | آن‌ها را یکی کن: type Shape = Circle | Rect;. فیلد kind مثل برچسب روی جعبه است: می‌گوید داخلش چیست. به این می‌گویند union برچسب‌دار (tagged union).

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Circle | Rect;

const a: Shape = { kind: "circle", radius: 2 };
const b: Shape = { kind: "rect", width: 3, height: 4 };
show(a.kind, b.kind);
</script>

حالا همان دایره‌ی غلط را دوباره می‌نویسیم. اجرا کن: خط قرمز! برچسب می‌گوید circle، پس تایپ‌اسکریپت سراغ Circle می‌رود و می‌بیند radius نیست و width هم اضافه است. حالت غلط دیگر اصلاً نوشته نمی‌شود.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Circle | Rect;

const wrong: Shape = { kind: "circle", width: 5 };
show(wrong.kind);
</script>

داخل تابع، s یک Shape است: شاید دایره، شاید مستطیل. پس s.radius را مستقیم نمی‌شود خواند (خط قرمز می‌گیرد). اول برچسب را بپرس. داخل if (s.kind === "circle") تایپ‌اسکریپت می‌داند s یک Circle است و radius دارد. بعد از آن فقط Rect مانده است. دیگر ?? هم لازم نیست، چون هیچ فیلدی اختیاری نیست.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Circle | Rect;

function area(s: Shape): number {
  if (s.kind === "circle") {
    return 3 * s.radius * s.radius;
  }
  return s.width * s.height;
}

show(area({ kind: "circle", radius: 2 }));
show(area({ kind: "rect", width: 3, height: 4 }));
</script>

وقتی حالت‌ها زیاد می‌شوند، switch از چند if خواناتر است. switch (s.kind) برچسب را نگاه می‌کند و هر case یک حالت است. داخل هر case، تایپ‌اسکریپت شکل را باریک کرده است: در case "circle" فقط radius را می‌شناسد و در case "rect" فقط width و height را.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Circle | Rect;

function describe(s: Shape): string {
  switch (s.kind) {
    case "circle":
      return "circle, radius " + s.radius;
    case "rect":
      return "rect, " + s.width + " by " + s.height;
  }
}

show(describe({ kind: "circle", radius: 2 }));
show(describe({ kind: "rect", width: 3, height: 4 }));
</script>

یک نوع عجیب به اسم never داریم: نوعی که هیچ مقداری در آن جا نمی‌شود. به چه درد می‌خورد؟ در default یک switch، اگر همه‌ی حالت‌ها را نوشته باشی، دیگر چیزی برای s نمانده است، پس نوعش never است. خط const forgot: never = s; یعنی «قول می‌دهم این‌جا هیچ حالتی نمانده». تا وقتی همه‌ی caseها هستند، این خط بی‌صدا رد می‌شود.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

type Shape = Circle | Rect;

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":
      return 3 * s.radius * s.radius;
    case "rect":
      return s.width * s.height;
    default: {
      const forgot: never = s;
      return forgot;
    }
  }
}

show(area({ kind: "circle", radius: 2 }));
show(area({ kind: "rect", width: 3, height: 4 }));
</script>

حالا شش ماه بعد، یک نفر مثلث را به Shape اضافه می‌کند و یادش می‌رود area را به‌روز کند. اجرا کن: خط قرمز روی همان خط never. چرا؟ چون حالا در default یک Triangle مانده است، و Triangle در never جا نمی‌شود. تایپ‌اسکریپت دقیقاً نشانت می‌دهد کجا یک حالت را جا انداخته‌ای. بدون این خط، ممکن بود اصلاً نفهمی.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Circle {
  kind: "circle";
  radius: number;
}

interface Rect {
  kind: "rect";
  width: number;
  height: number;
}

interface Triangle {
  kind: "triangle";
  base: number;
  height: number;
}

type Shape = Circle | Rect | Triangle;

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":
      return 3 * s.radius * s.radius;
    case "rect":
      return s.width * s.height;
    default: {
      const forgot: never = s;
      return forgot;
    }
  }
}

show(area({ kind: "rect", width: 3, height: 4 }));
</script>

این الگو فقط برای شکل‌های هندسی نیست. هر چیزی که چند حالت دارد و هر حالت داده‌ی خودش را، همین‌طور نوشته می‌شود. مثلاً وضعیت یک صفحه: در حال بار شدن (بدون داده)، آماده (با امتیاز)، یا خطا (با پیام). حالا «آماده ولی بدون امتیاز» یا «خطا ولی با امتیاز» اصلاً نوشتنی نیست.

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
interface Loading {
  kind: "loading";
}

interface Done {
  kind: "done";
  score: number;
}

interface Failed {
  kind: "failed";
  message: string;
}

type State = Loading | Done | Failed;

function view(state: State): string {
  switch (state.kind) {
    case "loading":
      return "Please wait...";
    case "done":
      return "Score: " + state.score;
    case "failed":
      return "Error: " + state.message;
  }
}

show(view({ kind: "loading" }));
show(view({ kind: "done", score: 18 }));
</script>

مثال‌های این جلسه

چالش‌ها

  1. Fix the Red Line (آسان)
  2. Cat or Dog (آسان)
  3. Square and Rectangle (متوسط)
  4. The Forgotten Bomb (متوسط)
  5. Find the Red Lines (سخت)
  6. Moves of a Fight (سخت)

بیشتر بخوان

← جلسه‌ی 18: شاید هیچ جلسه‌ی 20: پروژه: چراغ راهنمایی‌ای که اشتباه نمی‌کند →