본문 바로가기

클라이언트/TypeScript
[타입스크립트(TypeScript)] 인터페이스(Interface)

// 인터페이스, Interface

- 객체의 구조를 정의한다.

- 객체의 타입을 정의할 때는 커스텀 타입보다 명확하게 나타낼 수 있는 인터페이스를 주로 사용한다.

- 여러 클래스에서 기능을 공유하기 위해서도 인터페이스를 사용한다.


// 인터페이스 정의

interface 인터페이스명 {
  property명:타입;

  메소드명: 반환타입;
}


- interface 키워드를 붙인다.

- interface 명은 대문자로 시작하는 것이 관례이다.

- property에 값을 할당할 수 없고 타입만 정의한다.


// 인터페이스 사용

// 객체
let 변수명: 인터페이스명;

변수명 = {
  property명: 타입에 맞는 값,
  메소드명() {}
};

변수명.메소드명();

// 클래스
class 클래스명 implements 인터페이스명 {
  property명: 타입에 맞는 값;

  constructor() {}
  
  메소드명() {}
}

let 변수명: 인터페이스명;

변수명 = new 클래스명();


- 객체의 경우 인터페이스에 정의한 property와 메소드를 모두 구현해야 한다. 

- class에서 인터페이스를 받을 때는 implements를 사용한다.(extends XXX!)


- 객체

interface Greetable {
  name: string;

  greet(phrase: string): void;
}

user1 = {
  name: 'Hana',
  age: 27,
  greet(phrase: string) {
    console.log(`${phrase} I'm ${this.name}`);
  },
};

user1.greet('Hi- there,');

- 클래스

interface Greetable {
  name: string;

  greet(phrase: string): void;
}

class Person implements Greetable {
  name: string;
  age: number = 27;

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

  greet(phrase: string) {
    console.log(`${phrase} I'm ${this.name}, and I'm ${this.age} years old.`);
  }
}

let user1: Greetable;

user1 = new Person('Hana');
user1.greet('Hi~~');

// extends

- 인터페이스끼리 확장된다.

- 인터페이스를 분리하여 관리한다.

- property나 method 자유도를 높여줄 수 있다.

interface 인터페이스명1 {
  property명: 타입
}

interface 인터페이스명2 extends 인터페이스명1 {
  method명(): 반환 타입;
}

interface Named {
  readonly name: string;
}

interface Greetable extends Named {
  greet(phrase: string): void;
}

// 함수 type

- 함수의 구조를 인터페이스로 정의한다.

- 익명함수로 정의한다.

interface 인터페이스명 {
  (매개변수: 타입): 반환타입;
}

let 함수명: 인터페이스명;

함수명 = (매개변수: 타입) => {
  return 반환;
}

interface AddFn {
  (a: number, b: number): number;
}

let add: AddFn;

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