TypeScript | extends / implements

Kate Jung·2022년 1월 30일
0

TypeScript

목록 보기
7/10
post-thumbnail

📌 extends

클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용

🔹 클래스의 .prototype

Object or null

  • null 일 경우

    의미: 프로토타입 체인의 최상단

🔹 예시 코드

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
}

class KMJ extends Person {
  sayHi() {
    console.log(`hi, ${this.name}`)
  }
}

const mj = new KMJ('kmj', 10)
console.log(mj.sayHi()) // output: hi, kmj

📌 implements

classinterface에 만족하는지 여부를 체크할 때 사용

🔹 특징

  • TS에서 interface & class 동시 확장 가능

  • implementsinterface의 타입이 없다면 → 에러 반환

    • 예시 코드
        interface Person {
          name: string
          age: number
        }
        
        // 에러: age 미정의
        class Howdy implements Person {
          // Class 'Howdy' incorrectly implements interface 'Person'.
          // Property 'age' is missing in type 'Howdy' but required in type 'Person'.
          name = 'howdy'
        }
  • 오직 타입 체크를 위해 사용

    • 안의 값을 자동으로 바꾸지 x

    • 예시 코드

        interface Person {
          name: string
          age: number
          isMJ(name: string): boolean
        }
        
        class Howdy implements Person {
          name = 'howdy'
          age = 20
        
          isMJ(name) {
            // 에러: parameter의 타입 미지정
            // Parameter 'name' implicitly has an 'any' type, but a better type may be inferred from usage.
            return this.name === 'kmj'
          }
        }

📌 비교표


참고

profile
복습 목적 블로그 입니다.

0개의 댓글