TypeScript

인터페이스와 클래스의 관계

KimJye 2019. 10. 30. 18:32

클래스의 인터페이스 구현

인터페이스는 본질적으로 값이 어떤 멤버를 반드시 가져야 하며 그 멤버들의 타입은 어때야 한다는 제약을 나타내는 수단이다.

implements 키워드를 사용해 클래스가 이러한 제약을 따라야 함을 표현할 수 있다.

    interface Animal {
      legs: number;
    }

    class Dog implements Animal {
      legs: number = 4;
    }
    // Okay

인터페이스의 클래스 확장

인터페이스 확장과 유사하게 extends 키워드를 사용해 클래스를 확장할 수 있다. 공식 문서에 있는 예제를 살펴보자.

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

    interface Point3d extends Point {
        z: number;
    }

    const point3d: Point3d = {x: 1, y: 2, z: 3};