Browse Source

4.5: Enums, arrays (generics) and tuples.

Frederic G. MARAND 5 years ago
parent
commit
ec46ef5362
1 changed files with 36 additions and 0 deletions
  1. 36 0
      app/app.ts

+ 36 - 0
app/app.ts

@@ -1,3 +1,39 @@
+enum Category {
+  Biography,     // 0
+  Poetry,        // 1
+  Fiction,       // 2
+}
+enum Category2 {
+  Biography = 1, // 1
+  Poetry,        // 2
+  Fiction,       // 3
+}
+enum Category3 {
+  Biography = 1, // 1
+  Poetry = 5,    // 5
+  Fiction = 0,   // 0
+}
+
+let favoriteCategory: Category = Category.Fiction;
+console.log(favoriteCategory, Category[favoriteCategory], Category['Fiction'], Category[Category['Fiction']], Category);
+
+let strArray1: string[] = ['a', 'strings', 'array'];
+// "Generics" syntax.
+let strArray2: Array<string> = ['another'];
+
+// A plain Array wouldn't work: in this case Array is the TS generic, not the
+// JS builtin.
+let mixedArray1: Array<any> = [42, true, 'banana'];
+let mixedArray2: any[] = [42, true, 'banana'];
+let mixedArray3: (number|boolean|string)[] = [42, true, 'banana'];
+let mixedArray4 = [42, true, 'banana'];
+
+let myTuple: [number, string] = [25, 'truck'];
+let [firstElement, secondElement] = myTuple;
+myTuple[2] = 'book';
+// But not: myTuple[0] = 'book';
+// Nor: myTuple[2] = {}
+
 function GetAllBooks() {
   let books = [
     {