그럼에도 불구하고

👨‍💻

[TypeScript] extends와 implements의 차이 본문

TypeScript/TypeScript basics

[TypeScript] extends와 implements의 차이

zenghyun 2023. 5. 4. 17:13

extends와 implements의 차이에 대해 알아보겠습니다.

 

 

자바스크립트에서 어떤 클래스를 상속받고 싶을 때 하위 클래스에 extends 키워드를 사용하면 상속받을 수 있습니다.

그리고 타입스크립트에서는 implements 키워드를 통해서, interface와 class를 동시에 확장할 수 있습니다.

 

 

[ extends ]

extends 키워드는 class 선언문이나 class 표현식에서 만들고자 하는 class의 하위 클래스를 생성할 때 사용할 수 있습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
}
 
class Hello extends Person {
  sayHi() {
    console.log(`hi, ${this.name}`)
  }
}
 
const zenghyun = new Hello('Zenghyun'27)
console.log(zenghyun.sayHi()) // output: hi, Zenghyun
cs

 

 

[ implements ]

implements 키워드는 class의 interface에 만족하는지 여부를 체크할 때 사용됩니다. implements 한 interface의 타입이 없다면 에러를 반환합니다.

 

1
2
3
4
5
6
7
8
9
10
11
interface Person {
  name: string
  age: number
}
 
// 에러: age 미정의
class Info implements Person {
  // Class 'Info' incorrectly implements interface 'Person'.
  // Property 'age' is missing in type 'Info' but required in type 'Person'.
  name = 'Zenghyun'
}
cs

 

여기서 주의할 점은, implements는 오직 타입 체크를 위해 사용되는 것이지, 안의 값을 자동으로 바꾸어주지 않는다는 것입니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
interface Person {
  name: string
  age: number
  showInfo(name: string): boolean
}
 
class Info implements Person {
  name = 'Zenghyun'
  age = 27
 
  showInfo(name) {
    // 에러: parameter의 타입 미지정
    // Parameter 'name' implicitly has an 'any' type, but a better type may be inferred from usage.
    return this.name === 'lzh'
  }
}
 
cs

 

 

[ 결론 ]

extends 키워드는 새로운 클래스의 '상속'을 위해 사용합니다. 상위 클래스의 모든 프로퍼티와 메서드들을 갖고 있으므로 일일이 정의하지 않아도 됩니다. 또한 상위 클래스의 프로퍼티를 지정하지 않으면, 초기값으로 선언되며 에러를 반환하지 않습니다.

 

implements 키워드는 새로운 클래스의 모양을 동일하게 정의하고 싶을 때 사용합니다. 따라서, interface로 정의한 값들은 모두 필수적으로 들어가야 하며, 하나라도 빠질 경우 에러를 반환합니다. 타입으로 지정한 메서드 모두 내부에서 재정의가 필요합니다. 

 

Comments