본문 바로가기
Language/TypeScript

[TypeScript] 인터페이스(interface) (ft. Intersection)

by 썸머워즈 2022. 6. 8.
반응형

javascript에는 지원하지 않던 인터페이스에 대해 알아보자.

Typescript에서 인터페이스는 타입 체크를 한다거나, 클래스에 사용한다거나 등의 역할을 가지고 있다.

 

몇 가지 특징과 사용법에 대해 알아보자.


1. 타입 체크용 인터페이스

여기서의 인터페이스는 typescipt에서 제공하는 type 이랑 동일한 역할을 한다.

interface Point {
  x: number;
  y: number;
}

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}

let point: Point = {
  x: 100,
  y: 100,
};

printCoord(point);

이렇게 인터페이스를 사용한다면 타입 별칭과 별다른 차이점이 없다.

그러나 신기하게도 타입 별칭에서는 허용이 안됐지만 인터페이스에서는 허용이 되는 부분이 있는데 바로 Intersection이다.

 

같은 이름의 타입 별칭을 사용할 경우 에러가 발생하지만 인터페이스의 경우 같은 이름의 인터페이스가 선언될 경우 두 인터페이스가 하나로 합쳐진다. (여기서 물론 주의할 점은 같은 이름의 다른 타입을 가졌을 경우 에러가 발생한다.)

interface Point {
  x: number;
  y: number;
}

interface Point {
  z: number;
}

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
  console.log("The coordinate's z value is " + pt.z);
}

let point: Point = {
  x: 100,
  y: 10,
  z: 1,
};

printCoord(point);

 

2. 클래스에서의 인터페이스

역시 본격적으로 인터페이스를 활용하는 부분은 클래스에서의 인터페이스가 아닌가 싶다.

클래스 기반 객체 지향 언어에서는 규모와 설계에 따라 인터페이스를 많이 사용하는데, 하나의 규격을 만들어 사용하게 도와주기 때문이다.

 

추상 클래스와는 다르게 abstract를 선언하지 않으며, 인터페이스 그 자체로 추상적이기 때문에 인터페이스를 구현(implements) 하게 되면 그 안에 선언된 규격들을 반드시 구현해야 한다.

interface Animal {
  readonly gender: string;
  howling(): void;
  setName(name: string): string;
}

class Dog implements Animal {
  constructor(private name: string, private _gender: string) {}
  get gender(): string {
    return this._gender;
  }
  howling(): void {
    console.log("dooooooooooog!");
  }
  setName(name: string): string {
    this.name = name;
    return this.name;
  }
}

이런 식으로 interface를 통해 공통 규격을 정해놓고 그것을 클래스에서 구현하는 형식으로 많이 사용된다.

당연히 객체 지향 언어에서 사용되는 인터페이스와 동일하게 지원되기 때문에 다중 상속, 다중 구현이 가능하다.


참고: https://poiemaweb.com/typescript-interface

 

TypeScript - Interface | PoiemaWeb

인터페이스는 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있다. 인터페이스는 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다.

poiemaweb.com

반응형


댓글

TOP