Post
TS) 인터페이스
2022-09-25 AM 08/10
#typescript
#study
1. 인터페이스
인터페이스는 속성 외 메서드도 지정할 수 있다.
interface MoterVehicle{
엔진: boolean;
색깔: string;
엑셀가동(speed: number;);
브레이크(): boolean;
}
인터페이스를 활용한 클래스
class Car implements MotoVehicle{
}
하지만, 클래스 선언은 컴파일되지 않는다.
인터페이스로 클래스를 선언할 때, 인터페이스 내 각 메서드를 구현해야 한다.
즉, 위 코드는 Car 클래스가 MotorVehicle 인터페이스에 선언된 API를 반드시 구현할 것임을 약속하는 것과 같다.
여러 개의 인터페이스로 클래스 구현하기
interface MoterVehicle{
엔진: boolean;
색깔: string;
엑셀가동(speed: number;);
브레이크(): boolean;
}
interface Flyable {
비행(howhigh: number);
착륙();
}
interface Swimmable {
잠수(howFar: number);
}
class Car implements MotorVehicle, Flyable, Swimmable{
// 세가지 인터페이스 내 모든 메서드를 구현해야함!
}
2. 인터페이스 확장
class SecretServiceCar implements MotorVehicle, Flyable, Swimmable{
// 세 가지 인터페이스를 구현하는 클래스
}
인터페이스 확장
interface MotorVehicle{
엔진: boolean;
색깔: string;
엑셀가동(speed: number);
브레이크(): boolean;
}
interface Flyable extends MotorVehicle {
비행(howHigh: number);
착륙();
}
Flyable로 생성한 클래스는 총 6개의 메서드를 구현해야 한다.
3. 인터페이스 프로그래밍
- 구현 프로그래밍
class Product {
id: number;
description: string;
}
class ProductService {
getProduct(): Product[]{
// Get all product information
return [];
}
getProductById(id: number): Product{
return {id: 123, desc: '제품임 ㅋ'}
}
}
이후 ProductSerice 인스턴스를 만들고 메서드를 사용할 수 있다.
하지만, 아직 서버가 준비되지 않아서 동일한 API를 사용하는 MockProductService 클래스를 생성해야 한다면?
class MockProductService {
getProduct(): Product[]{
// Get all product information
return [];
}
getProductById(id: number): Product{
return {id: 123, desc: '모킹 데이터 제품임 ㅋ'}
}
}
MockProductSerivce는 ProductService 클래스와 동일한 메서드를 가져야 한다.
implements 키워드 뒤에 다른 클래스를 적으면, 뒤의 클래스를 강제 구현하도록 한다.
class MockProductService implements ProductService {
}
- 인터페이스 프로그래밍
이번에는 인터페이스 프로그래밍에 대해서 알아보자
interface Product {
id: number;
description: string;
}
interface IProductService {
getProducts(): Product[];
getProductById(id: number): Product;
}
class ProductService implements IProductService {
getProducts(): Product[]{};
getProductById(id: number):Product {};
}
class MockProductService implements IProductService {
getProducts(): Product[]{};
getProductById(id: number):Product {};
}
Product를 초기화할 필요가 없을 때, class 대신 interface 키워드를 사용하면 자바스크립트 코드량이 적어진다.
인터페이스 프로그래밍의 예) 팩토리 함수
팩토리 함수는 비지니스 로직을 구현하고 객체의 인스턴스를 반환하는 함수
function getProductService(idProduction: boolean):IProductService {
if(isProduction) {
return new ProductService();
} else {
return new MockProductService();
}
}
const productService: IProductService; // 인터페이스 타입을 나태는 상수
const isProd = true; // 현재 프로덕션 상태
productService = getProductService(isProd); // productService 인스턴스를 가져온다.
const products[] = productService.getProducts(); // productService 내 메서드를 호출한다.
Summary
- 상속이란 기존에 정의되어 있는 클래스의 모든 멤버를 물려받아 새로운 클래스를 생성하는 것
- super, super() 메서드로 서브클래스가 슈퍼클래스의 멤버를 호출할 수 있다.
- 인터페이스는 메서드 시그니처를 선언할 수 있지만, 구현은 할 수 없다.
- 인터페이스를 다른 인터페이스로 상속할 수 있다. (implements)
- 클래스 구현 시, 인터페이스에서 선언해야 할 메서드가 있는 지 먼저 확인하자!(인터페이스 기반 프로그래밍)
메서드 선언과 구현을 깔끔하게 할 수 있게 된다.