جواب «Step 1: The Store» چالش 1 از جلسهی 30
سؤال
قدم اول: کلاس Store را بنویس. خطهای پایینِ کد از آن استفاده میکنند و تا کلاس را نسازی قرمزند.
- class Store<T extends { id: number }>
- یک فیلد خصوصی: private items: T[] = [];
- add(item: T): void که یک چیز را به items اضافه میکند.
- all(): T[] که همهی چیزها را برمیگرداند.
برنامه باید 2 را نشان بدهد.
راهنما
داخل add: this.items.push(item); و داخل all: return this.items;
یک جواب درست
<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 Book {
id: number;
title: string;
price: number;
}
class Store<T extends { id: number }> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
all(): T[] {
return this.items;
}
}
const books = new Store<Book>();
books.add({ id: 1, title: "Matilda", price: 80 });
books.add({ id: 2, title: "Holes", price: 95 });
show(books.all().length);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن