인터페이스

  • 인터페이스를 인자로 받아 사용할 때 항상 인터페이스의 속성 갯수와 인자로 받는 객체의 속성 갯수를 일치시키지 않아도 된다. 다시 말해, 인터페이스에 정의된 속성, 타입의 조건만 만족한다면 객체의 속성 갯수가 더 많아도 상관 없다는 의미입니다.
  • 인터페이스에 선언된 속성 순서를 지키지 않아도 됩니다.

옵션 속성

interface personAge {
  age: number;
  name: string;
}

function logAge(obj: personAge) {
  console.log(obj.age);
  console.log(obj.name);
}
let person = { age: 28 , hop: 89};
logAge(person); // ERROR: Argument of type '{ age: number; hop: number; }' is not assignable to parameter of type 'personAge'.   Property 'name' is missing in type '{ age: number; hop: number; }' but required in type 'personAge'.

만약에 name이 옵션 속성을 가지고 있다면?

interface personAge {
  age: number;
  name?: string;
}

logAge() 함수가 에러나지 않고

28

undefined

를 출력한다.

// Example
interface Person {
    firstName: string;
    middleName?: string;
    lastName: string;
}

function getFullName(person: Person) {
    if (person.middleName) {
        return `${person.firstName} ${person.middleName} ${person.lastName}`;
    }
    return `${person.firstName} ${person.lastName}`;
}

readonly 속성

  • 읽기 전용 속성은 인터페이스로 객체를 처음 생성할 때만 값을 할당하고 그 이후에는 변경할 수 없는 속성을 의미합니다.
interface CraftBeer {
    readonly brand: string;
}

let myBeer: CraftBeer = {
    brand: 'Belgian Monk'
};

myBeer.brand = 'Korean Carpenter'; // error: Cannot assign to 'brand' because it is a read-only property.

 

함수 타입

  • 인터페이스에 함수를 정의하고 변수에 이 인터페이스를 할당하면 함수를 만들 때 매개변수와 반환값의 타입을 정의하지 않아도 된다.
  • 매개변수의 이름이 달라도 가능하며 순서대로 매치가 된다.
interface login {
    (username: string, passwrod: string, id?: string): boolean;
  }
 
  let loginUser: login;
  loginUser = function(name, pw, id) {
    console.log('로그인 했습니다: '+ name);
    return true;
  }
 
  let loginUser2 = function(n: any,p: any,i: any): boolean {
      console.log(n,p,i);
      return true;
  }
 
  console.log(loginUser('a','b'));
  console.log(loginUser2('a','b','c'));

 

클래스 

  • 인터페이스는 클래스와 비슷한데, 클래스와 달리 정의만 할 뿐 실제 구현되지 않습니다. 즉, 어떠한 객체를 생성 했을 때 가져야 할 속성 또는 메서드를 정의한다고 보면 됩니다. (추상 클래스와 유사해보입니다)
  • Y9Button 클래스 안에서 ButtonInterface 인터페이스에 정의한 onClick()과 onInit()을 구현하지 않으면 에러가 난다.
interface ButtonInterface {
onInit():void;
onClick():void;
}

// 클래스 Y9Button 인터페이스 Button 확장
class Y9Button implements ButtonInterface {

width:number;
height:number;

constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
};

onClick() {
    console.log('click');
};

onInit() {
    console.log('init');
};

}

let button = new Y9Button(1,2);
button.onInit(); // "init"

 

인터페이스 확장

interface B {
    b(): void
}

interface C {
    c(): void
}

interface D extends B, C {
    d(): void
}

 

하이브리드 타입

interface CraftBeer {
    (beer: string): string;
    brand: string;
    brew(): void;
  }
 
  function myBeer(): CraftBeer {
    let my = (function(beer: string) {}) as CraftBeer;
    my.brand = 'Beer Kitchen';
    my.brew = function() {};
    return my;
  }
 
  let brewedBeer = myBeer();
  brewedBeer('My First Beer');
  brewedBeer.brand = 'Pangyo Craft';
  brewedBeer.brew();

 

출처 

https://yamoo9.gitbook.io/typescript

https://www.typescripttutorial.net/typescript-tutorial/typescript-interface/

https://joshua1988.github.io/ts/guide/interfaces.html

 

 

 

'개발 > Javascript(Typescript)' 카테고리의 다른 글

[디자인 패턴] 싱글톤  (0) 2023.08.08
타입스크립트 4 - 클래스  (0) 2023.07.21
타입스크립트 2 - 함수  (0) 2023.07.17
자바스크립트 this  (0) 2023.07.14
타입스크립트 1 - 기본 타입  (1) 2023.07.13

+ Recent posts