TypeScript [ 공부 : extends VS implements ]
자바스크립트에서 어떤 클래스를 상속받고 싶을 때는 하위 클래스에서 extends 키워드를 통해 상속 받을 수 있다.
그리고 타입스크립트에서는 implements 키워드를 통해서, interface와 class를 동시에 확장 가능한 것을 알고 있었다.
객체지향을 공부하다가 Java에도 똑같이 implements와 extends가 있는 것을 보았고
이 두 가지의 정확한 차이점을 알기 위해서 찾아보았다.
본문
extends vs. implements
extends
extends 키워드는 class 선언문이나 class 표현식에서 만들고자하는 class의 하위 클래스를 생성할 때 상속하기 위해서 사용한다.
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
}
class Student extends Person {
sayHi() {
console.log(`hi, ${this.name}`)
}
}
const me = new Student('Choo', 25)
console.log(mj.sayHi()) // output: hi, Choo

클래스의 `.prototype`은 반드시 Object이거나 null이어야 한다. null일 경우, 프로토타입 체인의 최상단을 뜻한다.


implements
`implements` 키워드는 `class`의 `interface`에 만족하는지 여부를 체크할 때 사용된다.
`implements`한 `interface`의 타입이 없다면 에러를 반환한다.
interface Person {
name: string;
age: number;
}
// 에러: age 미정의
class Student implements Person {
// Class 'Student' incorrectly implements interface 'Person'.
// Property 'age' is missing in type 'Student' but required in type 'Person'.ts(2420)
name = 'Choo';
}
여기서 주의할 점은, implements는 오직 타입 체크를 위해 사용되는 것이지, 안의 값을 자동으로 바꾸어주지 않는다.
타입스크립트 타입의 특징 (타입을 잘 정하자!!)
interface Person {
name: string;
age: number;
isSame(name: string): boolean;
}
class Student implements Person {
name = 'Choo';
age = 22;
isSame(name) {
// error: parameter의 타입 미지정
// Parameter 'name' implicitly has an 'any' type, but a better type may be inferred from usage.
return this.name === name;
}
}
결론
extends 키워드는 새로운 클래스의 ‘상속’을 위해 사용한다.
- 상위 클래스의 모든 프로퍼티와 메서드들을 갖고 있으므로 일일이 정의하지 않아도 된다.
- 상위 클래스의 프로퍼티를 지정하지 않으면, 초기값으로 선언되며 에러는 반환하지 않는다.
implements 키워드는 새로운 클래스의 특정 모양을 동일하게 정의하고 싶을 때 사용한다.
- interface로 정의한 값들은 모두 필수적으로 들어가야 하며, 하나라도 빠질 경우 에러를 반환한다.
- 타입으로 지정한 메서드 모두 내부에서 재정의가 필요하다.
부모클래스는 보통 1개만 사용함 왜냐하면 많은 언어가 그렇게 지원을 하고
2개 이상이 가능하더라도 예상하지 못한 오류가 나올 가능성이 큼
reference
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/extends
- https://www.typescriptlang.org/docs/handbook/2/classes.html#extends-clauses
- https://www.typescriptlang.org/docs/handbook/2/classes.html#implements-clauses
- What’s the difference between ‘extends’ and ‘implements’ in TypeScript