Przeglądaj źródła

9.4 generic functions.

Frederic G. MARAND 5 lat temu
rodzic
commit
438db2f101
3 zmienionych plików z 37 dodań i 1 usunięć
  1. 17 1
      app/app.ts
  2. 19 0
      app/generics.ts
  3. 1 0
      app/lib/utilityfunctions.ts

+ 17 - 1
app/app.ts

@@ -1,8 +1,9 @@
 import {Book, Logger as DamageLogger, Librarian} from './interfaces';
 import {Category} from './enums';
-import {ReferenceItem, UniversityLibrarian} from './classes';
+import {Journal, ReferenceItem, UniversityLibrarian} from './classes';
 import { CalculateLateFees as CalcFee, MaxBooksAllowed }  from './lib/utilityfunctions';
 import refBook from './encyclopedia';
+import { LogAndReturn }from './generics';
 
 export function GetAllBooks(): Book[] {
   const books = [
@@ -200,6 +201,21 @@ function importDemo() {
   console.log(ref);
 }
 
+function genericFunctionDemo() {
+  LogAndReturn(false);
+  LogAndReturn(42);
+  LogAndReturn({ a: []});
+
+  interface Magazine { title: string }
+
+  let someString: string = LogAndReturn<string>('log this');
+  console.log("Returned: ", someString);
+  let newMag: Magazine = { title: 'Web dev monthly' };
+  let someMag: Magazine = LogAndReturn<Magazine>(newMag);
+  console.log('Returned mag', someMag);
+}
+
 false && bookDemo();
 false && classDemo();
 false && importDemo();
+genericFunctionDemo();

+ 19 - 0
app/generics.ts

@@ -0,0 +1,19 @@
+import {Book} from "./interfaces";
+
+export type Books = Array<Book>;
+
+export function booksTest() {
+
+  let poetryBooks: string[] = ['a'];
+  let fictionBooks: Array<string> = ['b'];
+
+  let historyBooks = new Array<Book>(5);
+  // Forbidden
+  // let historyBooks: Books = new Books(5);
+  console.log(poetryBooks, fictionBooks, historyBooks);
+}
+
+export function LogAndReturn<T>(thing: T): T {
+  console.log(thing);
+  return thing;
+}

+ 1 - 0
app/lib/utilityfunctions.ts

@@ -16,4 +16,5 @@ function privateFunc(): void {
   console.log('This is private...');
 }
 
+false && privateFunc();
 export { CalculateLateFees, MaxBooksAllowed };