TypeScript - implements

꼬디바아 ㅣ 2024. 3. 19. 17:27

728x90

TypeScript 대표이미지

 

Implements 키워드

클래스가 특정 인터페이스를 구현할 때 사용된다. JavaScript를 보완하여 정적 타입 검사를 지원하는 TypeScript에서는 인터페이스를 사용하여 코드의 구조를 정의하고, 클래스가 해당 구조를 따르도록 강제할 수 있다.

 

class Car {
  model : string;
  price : number = 1000;
  constructor(a :string){
    this.model = a
  }
}
let 붕붕이 = new Car('morning');

 

class Car로 부터 생산되는 object들은 model과 price 속성을 가지게 된다. 근데 class가 model, price 속성을 가지고 있는지 타입을 확인하고 싶다면 interfece + implements 키워드로 확인하면 된다.

 

interface CarType {
  model : string,
  price : number
}

class Car implements CarType {
  model : string;
  price : number = 1000;
  constructor(a :string){
    this.model = a
  }
}
let sportCar = new Car('morning');

 

class 이름 우측에 implements를 쓰고 interface 이름을 쓰면 이 class가 interface에 있는 속성을 들고 있는지 확인하게 된다.

 

여기서 알아야할 것은 implements는 타입 지정문법이 아니다.

implements라는건 interface에 들어있는 속성을 가지고 있는지 확인만 하는 것이지 class에 필드와 타입을 할당하고 변형시키는 역할이 아니다.

 

Q. 그렇다면 implements는 어떤 곳에서 쓰일까?

위에 설명 했듯이 class가 특정 필드와 함수를 가지고 있는지 확인하고 싶은 경우 간혹 사용한다.

 

예를 들어 클래스끼리 복잡하게 상속하는 경우 class에 어떤 필드와 함수가 들어있는지 추론하기 힘든 경우가 많다. 그래서 class가 특정 필드와 함수를 가지고 있는지 확인하고 싶을 때 사용하면 된다.

 

728x90

'👨‍💻 TypeScript' 카테고리의 다른 글

TypeScript - type mapping  (0) 2024.03.20
TypeScript - Index signature  (0) 2024.03.19
TypeScript - declare  (0) 2024.03.19
TypeScript - TypeScript + Redux  (0) 2024.03.19
TypeScript - React + Typescipt  (0) 2024.03.17