جواب «Types for the Counter» چالش 3 از جلسهی 21
سؤال
این کلاس را کسی به سبک جاوااسکریپت نوشته است: هیچ نوعی ندارد و پر از خط قرمز است.
نوعها را بنویس:
- بالای سازنده فیلد count را با نوع number معرفی کن.
- ورودی start در سازنده و ورودی n در add هر دو number هستند. add چیزی برنمیگرداند (void).
برنامه باید بنویسد: 8 و در خط بعد 10
راهنما
خط اول کلاس: count: number;. بعد constructor(start: number) و add(n: number): void.
یک جواب درست
<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">
class Counter {
count: number;
constructor(start: number) {
this.count = start;
}
add(n: number): void {
this.count = this.count + n;
}
}
const counter = new Counter(5);
counter.add(3);
show(counter.count);
counter.add(2);
show(counter.count);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن