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

The Honest Guard چالش 3 از جلسه‌ی 33، متوسط

نگهبانِ isPlayer تنبل است: همیشه true می‌گوید. برای همین برنامه چیزهای غلط می‌نویسد و آخرش هم می‌ایستد.
داخل isPlayer را درست بنویس. فقط وقتی true برگردان که:
- value یک شیء باشد و null نباشد،
- فیلدهای name و score را داشته باشد،
- name متن و score عدد باشد.
بقیه‌ی برنامه را عوض نکن. خروجی باید این پنج خط باشد:
Sara has 12، و بعد چهار بار Bad data

<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 Player {
  name: string;
  score: number;
}

function isPlayer(value: unknown): value is Player {
  return true;
}

function report(text: string): void {
  const data: unknown = JSON.parse(text);
  if (isPlayer(data)) {
    show(data.name + " has " + data.score);
  } else {
    show("Bad data");
  }
}

report('{"name": "Sara", "score": 12}');
report('{"name": "Ali"}');
report('{"name": "Reza", "score": "ten"}');
report("7");
report("null");
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 33: داده از بیرون · چالش بعدی: The Pet Card

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js