Browse Source

5.5: creating interfaces.

Frederic G. MARAND 5 years ago
parent
commit
0f437501ba
4 changed files with 46 additions and 2 deletions
  1. 12 0
      app/app.ts
  2. 2 2
      app/enterprise.ts
  3. 23 0
      app/person.ts
  4. 9 0
      app/result.ts

+ 12 - 0
app/app.ts

@@ -51,3 +51,15 @@ const logMessage = (message: string) => console.log(message);
 function logError(message: string): void {
   console.error(message);
 }
+
+let myResult: Result = {
+  playerName: 'Marie',
+  score: 5,
+  problemCount: 5,
+  factor: 7,
+};
+
+let player: Person = {
+  name: 'Daniel',
+  formatName: () => 'Dan',
+};

+ 2 - 2
app/enterprise.ts

@@ -20,11 +20,11 @@ let dev = {
   editor: 'VSCode',
 };
 
-let employee : Employee = dev;
+let newEmployee : Employee = dev;
 
 function foo(e: Employee) {
   console.log(e.name + ": " + e.title);
 }
 
 foo(dev);
-foo(employee);
+foo(newEmployee);

+ 23 - 0
app/person.ts

@@ -0,0 +1,23 @@
+interface Person {
+  // If age exists, then it must be a number; but it is not required to exist.
+  age?: number;
+  formatName: () => string;
+  name: string;
+}
+
+abstract class FooBase {
+  age: number;
+  name: string;
+}
+
+class Foo extends FooBase implements Person {
+  constructor(props: string[]) {
+    super();
+    this.age = 0;
+    this.name = "Doe";
+  }
+
+  formatName(): string {
+    return this.name;
+  }
+}

+ 9 - 0
app/result.ts

@@ -0,0 +1,9 @@
+// Could have been a class, but since there are no methods involved, an
+// interface is cheaper (translates to just nothing in compiled code, unlike a
+// class).
+interface Result {
+  playerName: string;
+  score: number;
+  problemCount: number;
+  factor: number;
+}