[Typescript] ✨extends vs implements

미누·2023년 4월 4일
0

TypeScript

목록 보기
6/6

Extends

extends에 원하는 클래스를 명시하면 해당 클래스의 프로퍼티와 메서드를 따로 구현하지 않아도 인스턴스에서 자유롭게 사용 가능하다. ( 이미 상위 클래스의 멤버가 포함되어 있다. )

class Parent {
	public lastName: string = "An";
	public speakKorean() {
		console.log("안녕하세요");
	}
	public eatWithChopsticks() {
		console.log("젓가락으로 먹기");
	}
}

class Child extends Parent {}

let child = new Child();
console.log(child.lastName); //An
child.speakKorean(); //안녕하세요
child.eatWithChopsticks(); //젓가락으로 먹기

Implements

미리 추상화 된 인터페이스를 채택하여 사용하는 것
상속(extends)과는 달리 implements로 어떤 인터페이스를 채택하면 추상화 된 메서드나 프로퍼티를 반드시 구현해주어야한다.

interface Person {
  name: string;
  think(): void;
  walk(): void;
  eat(): void;
}

class Child extends Parent {}

class Child implements Person {
  name: string = "Fomagran";
  think(): void {
    console.log("생각하기");
}
  walk(): void {
    console.log("걷기");
  }
  eat(): void {
    console.log("먹기");
  }
}

어떤걸 extends하고, implements 할 수 있을까?

  • class extends class → 가능
  • class extends interface → 불가능 ⇒ implements
  • interface extends interface → 가능
  • interface extends class → 가능 ( 제약 사항이 있어 여기서는 다루지 않겠다. )
  • class implements class → 불가능
  • class implements interface → 가능
  • interface implements interface → 불가능 ⇒ 인터페이스가 구현되면, 해당 메소드를 정의해야하는데, 인터페이스는 정의할 수가 없기 때문이다.

출처 - [엘리스 강의 자료]

profile
Dev Notes, with bit of JS?

0개의 댓글