Quellcode durchsuchen

9.9: applying constraints to classes.

Frederic G. MARAND vor 5 Jahren
Ursprung
Commit
88b6b8e85a
4 geänderte Dateien mit 24 neuen und 9 gelöschten Zeilen
  1. 12 6
      app/app.ts
  2. 2 2
      app/classes.ts
  3. 5 0
      app/interfaces.ts
  4. 5 1
      app/shelf.ts

+ 12 - 6
app/app.ts

@@ -265,7 +265,7 @@ function getMagazinesInventory(): Array<Magazine> {
     },
     {
       publisher: 'GSU',
-      title: 'Give Points',
+      title: 'Five Points',
     }
   ];
 }
@@ -286,16 +286,22 @@ function genericClassDemo() {
   let bookShelf: Shelf<Book> = new Shelf<Book>();
   getBooksInventory().forEach(book => bookShelf.add(book));
   let firstBook: Book = bookShelf.getFirst();
-  console.log(firstBook);
+  // console.log(firstBook);
 
   let magazineShelf: Shelf<Magazine> = new Shelf<Magazine>();
   getMagazinesInventory().forEach(mag => magazineShelf.add(mag));
   let firstMagazine: Magazine = magazineShelf.getFirst();
-  console.log(firstMagazine);
+  // console.log(firstMagazine);
 
-  let numberShelf: Shelf<number> = new Shelf<number>();
-  [5, 10, 15].forEach(num => numberShelf.add(num));
-  console.log(numberShelf);
+  // No longer works after constraining Shelf<T extends ShelfItem>.
+  // let numberShelf: Shelf<number> = new Shelf<number>();
+  // [5, 10, 15].forEach(num => numberShelf.add(num));
+  // console.log(numberShelf);
+  magazineShelf.printTitles();
+
+  // Since bookShelf is Shelf<Book>, softwareBook is a Book.
+  let softwareBook = bookShelf.find('Code Complete');
+  console.log(`${softwareBook.title} (${softwareBook.author})`);
 }
 
 false && bookDemo();

+ 2 - 2
app/classes.ts

@@ -1,5 +1,5 @@
 import * as I from './interfaces';
-import {Inventory} from "./interfaces";
+import {CatalogItem, Inventory} from "./interfaces";
 
 class UniversityLibrarian implements I.Librarian {
   department: string;
@@ -46,7 +46,7 @@ class Journal extends ReferenceItem {
   }
 }
 
-class Catalog<T> implements Inventory<T> {
+class Catalog<T extends CatalogItem> implements Inventory<T> {
   private catalogItems = new Array<T>();
 
   addItem(newItem: T): void {

+ 5 - 0
app/interfaces.ts

@@ -14,6 +14,10 @@ interface Book {
   title: string,
 }
 
+interface CatalogItem {
+  catalogNumber: number;
+}
+
 interface DamageLogger {
   (reason: string): void;
 }
@@ -42,6 +46,7 @@ interface Person {
 export {
   Author,
   Book,
+  CatalogItem,
   DamageLogger as Logger,
   Inventory,
   Librarian,

+ 5 - 1
app/shelf.ts

@@ -1,7 +1,11 @@
+interface ShelfItem {
+  title: string;
+}
+
 /* There are lots of shelves in the library, and they can contain different
 types of objects.
  */
-export default class Shelf<T> {
+export default class Shelf<T extends ShelfItem> {
   private _items: Array<T> = new Array<T>();
 
   add(item: T): void {