[typescript] Interface

Suyeon·2020년 11월 12일
0

Typescript

목록 보기
6/12

Define the structure for an object for type checking.

  • Starting capital character is convention.

Interface vs type
Interface is used only for an object but type is not. So using interface makes you clear working with an object.

interface Person { // (*)
   name: string;
   age: number;
   greet: (phrase: string): void;
}

let user1: Person;

user1 = {
   name: 'Suyeon'.
   age: '25',
   greet(phrase: string) {
      console.log(phrase + this.name);
   }
}

user1.greet('Hey there');

Class and Interface

  • You can implement multiple interfaces.
  • Interface is often used to share functionality amongst different classes not regarding their concrete implementation.
interface Greetable {
   name: string;
   greet: (phrase: string): void;
}

class Person implements Greetable { // implements Greeatble, Person...
   name: string;
   age: 25;

   constructor(n: string) {
      this.name = n;
   }

   greet(phrase: string) {
      console.log(phrase + this.name);
   }
}

Readonly

  • You don't need set readonly to the field if you set it inside interface.
interface Greetable {
   readonly name: string; // (*)
   greet: (phrase: string): void;
}

Extending interface

  • you can extend multiple interfaces.
interface Named {
   readonly name: string; 
}

interface Greetable extends Named { // (*) extends Name, Another...
   greet: (phrase: string): void;
}

Interface as Function types

  • Alternative
// using type
type AddFunc = (a: number, b: number) => number;
let add: AddFunc;

add = (n1: number, n2: number) => {
     return n1 + n2;
}

// using interface
interface AddFunc {
  (a: number, b: number): number;
}

let add: AddFunc;

add = (n1: number, n2: number) => {
     return n1 + n2;
}

Optional property

  • You can use optional proprty on interface, class, and constructor separately.
// interface
interface Named {
   readonly name: string; 
   outputName? : string; // (*)
}
   
// class
interface Named {
   readonly name: string; 
   outputName? : string; // (*)
}
   
class Person implements Named {
   name?: string; // (*)
  
   constructor(n?: string) { // (*) OR set default value. n: string = "something"
      if(n) { 
         this.name = n;
      }
   }
}
profile
Hello World.

0개의 댓글