TS의 개념에 대해서 강의도 듣고 알 건 알았다. 문제는 내가 당장에 적용을 하기에 막막한데,
가장 기초적인 막막함: 그래서, 객체를 생성할때 class, type, interface 중에 뭘 사용하라는 거지?^^
예를 들어 Book이라는 객체를 만들고자 할 때 class, type, interface로 각각 예시를 들어보겠다.
1. class
(1) 정의하기
class Book {
constructor(
public title: string,
public author: string,
) { }
}
-> class로 정의할 때는 생성자를 호출해야 한다.
(2) 사용하기
const book = new Book("The Great Gatsby", "F. Scott Fitzgerald");
console.log(book.title); // "The Great Gatsby"
console.log(book.author); // "F. Scott Fitzgerald"
2. type
(1) 정의하기
type Book = {
title: string;
author: string;
}
(2) 사용하기
const book: Book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald"
};
// Book 객체의 속성 참조
console.log(book.title); // "The Great Gatsby"
console.log(book.author); // "F. Scott Fitzgerald"
- 사용 시 클래스처럼 생성자를 호출하는 것이 아니라 ,
이렇게 객체를 따로 생성해주고, 속성을 참조하는 방식으로 사용됨
3. interface
(1) 정의하기
interface Book {
title: string;
author: string;
}
- type과 정의방식은 동일 앞에 선언부만 "interface"
(2) 사용하기
// Book 객체 생성
const book: Book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald"
};
// Book 객체의 속성 참조
console.log(book.title); // "The Great Gatsby"
console.log(book.author); // "F. Scott Fitzgerald"
- 사용 방법도 동일: 객체생성 -> 참조
그렇다면 이 셋의 차이점은 뭘까?
class vs interface
- class는 객체의 구조 + 행동(메서드) 정의에 초점
생성(정의) 시, 속성 + 생성자(constructor)를 통해 초기화 + 데이터를 조작하는 메서드를 함께 캡슐화 가능
정의한 뒤 인스턴스를 만들어 직접 속성 및 메서드 호출 가능
class Book {
// 속성
private title: string;
private author: string;
// 생성자: 데이터 생성
constructor(title: string, author: string) {
this.title = title;
this.author = author;
}
// 메서드: 제목 조회
getTitle(): string {
return this.title;
}
// 메서드: 저자 조회
getAuthor(): string {
return this.author;
}
}
// 정의 후 Book 클래스의 인스턴스 생성
const book = new Book("The Great Gatsby", "F. Scott Fitzgerald");
// 인스턴스를 이용하여 속성 및 메서드 호출
console.log(book.title); // "The Great Gatsby"
console.log(book.author); // "F. Scott Fitzgerald"
console.log(book.getTitle()); // "The Great Gatsby"
console.log(book.getAuthor()); // "F. Scott Fitzgerald"
- interface는 객체의 형태와 구조에 초점
생성 시, class와 다르게 생성자로 데이터를 생성하거나 조작할 수 없음
class처럼 메서드 캡슐화는 가능
// 메서드 캡슐화 가능
interface RentManager {
getBooks(): Book[]; // 현재 도서목록을 확인하는 함수
addBook(user: User, book: Book): void; // 사서가 새로운 도서를 추가하는 함수
removeBook(user: User, book: Book): void; // 사서가 도서를 폐기
rentBook(user: Member, book: Book): void; // 사용자가 도서를 빌릴 때
returnBook(user: Member, book: Book): void; // 사용자가 도서를 반납할 때 호출하는 함수
}
interface vs type
- interface는 주로 객체의 형태와 구조 정의에 초점(어떤 속성과 어떤 메서드를 가져야하는지, 요구사항 명시)
=> 일종의 "규약" // 클래스나 다른 객체가 특정 interface를 따르도록 강제할 수 있음
- type은 주로 새로운 타입 정의 = 데이터의 종류 정의에 초점
=> 변수나 함수의 type 지정 // 클래스나 객체가 특정 type을 따르도록 강제할 수는 없음
확장& 상속
- interface는 가능 vs type은 불가능
재선언
- interface는 가능 vs type은 불가능
=> 협업 시 type이 더 깔끔할지도?
- type 은 조건부 타입(Conditional Types)을 포함하여 복잡한 타입 연산 수행가능