Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 그럼에도불구하고
- 자바
- 프론트엔드
- java
- github
- node
- webpack
- coding
- CSS
- 그럼에도 불구하고
- 반응형 페이지
- HTML
- 코딩테스트
- JS
- @media
- cleancode
- 자바문제풀이
- 변수
- Servlet
- frontend
- 코드업
- react
- redux
- media query
- JavaScript
- node.js
- TypeScript
- max-width
- react-router-dom
- git
Archives
- Today
- Total
그럼에도 불구하고
[TypeScript] extends와 implements의 차이 본문
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로 정의한 값들은 모두 필수적으로 들어가야 하며, 하나라도 빠질 경우 에러를 반환합니다. 타입으로 지정한 메서드 모두 내부에서 재정의가 필요합니다.
'TypeScript > TypeScript basics' 카테고리의 다른 글
[TypeScript] 이넘(Enum)의 특징 (1) | 2023.05.16 |
---|---|
[TypeScript] TypeScript로 Google Maps API 사용하기 (0) | 2023.05.13 |
[TypeScript] interface란? (0) | 2023.05.04 |
[TypeScript] 각종 실행 명령어 (0) | 2023.05.02 |
[TypeScript] TypeScript의 기본 타입 (0) | 2023.04.28 |
Comments