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

جواب «The Fruit Stand» چالش 4 از جلسه‌ی 29

سؤال

این برنامه موجودی یک میوه‌فروشی است. sell یکی از یک میوه کم می‌کند. ولی یک اشتباه بی‌صدا دارد: به‌جای "apple" نوشته شده "aple"، و چون جدول هر متنی را قبول می‌کند، هیچ خط قرمزی نیست. برنامه 3 نشان می‌دهد، در حالی که باید 2 باشد.
۱. یک نوع بساز: type Fruit = "apple" | "pear";
۲. نوع stock را Record<Fruit, number> کن و ورودی sell را Fruit.
۳. حالا غلط املایی قرمز می‌شود. درستش کن.
برنامه باید 2 و بعد 5 را نشان بدهد.

راهنما

const stock: Record<Fruit, number> = ... و function sell(fruit: Fruit): void { و در آخر sell("apple");

یک جواب درست

<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">
type Fruit = "apple" | "pear";

const stock: Record<Fruit, number> = { apple: 3, pear: 5 };

function sell(fruit: Fruit): void {
  stock[fruit] = stock[fruit] - 1;
}

sell("apple");
show(stock.apple);
show(stock.pear);
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن