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

جواب «One List, One Type» چالش 4 از جلسه‌ی 36

سؤال

این برنامه‌ی جاوااسکریپت جان‌های هر سطح را نشان می‌دهد. خط آخر یک غلط تایپی دارد (esay) و بی‌صدا 1 می‌نویسد.
۱. LEVELS را با as const قفل کن.
۲. از روی آن نوع بساز: type Level = typeof LEVELS[number];
۳. به lives نوع بده: ورودی Level، خروجی number.
۴. خط قرمز تازه غلط تایپی را نشان می‌دهد: درستش کن (easy).
خروجی: easy: 5، normal: 3، hard: 1 و در خط آخر 5.

راهنما

خط اول تابع: function lives(level: Level): number {. بعد از آن lives("esay") خط قرمز می‌گیرد.

یک جواب درست

<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">
const LEVELS = ["easy", "normal", "hard"] as const;
type Level = typeof LEVELS[number];

function lives(level: Level): number {
  if (level === "easy") {
    return 5;
  }
  if (level === "normal") {
    return 3;
  }
  return 1;
}

for (const level of LEVELS) {
  show(level + ": " + lives(level));
}
show(lives("easy"));
</script>

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