TIL

[ TypeScript ] 타입스크립트의 Classes 와 Interfaces.

dev_gggimmmin 2024. 3. 13. 21:09
728x90

 

 

Classes

 

추상(abstract)클래스

추상 클래스는 오직 다른 클래스가 상속 받을 수 있는 클래스이다.

하지만 직접 새로운 인스턴스를 만들 수는 없다.

// classes
abstract class User{
constructor(
private firstname:string,
private lastname:string,
public nickname:string
){
abstract getNickname():void
}
}

class Player extends User{
// 추상 메서드는 추상 클래스를 상속받는 클래스들이 반드시 구현(implement)해야하는 메서드이다.
getNickname(){
console.log(this.nickname)
}
}
접근 가능한 위치

구분              선언한 클래스 내     상속받은 클래스 내    인스턴스
private                     ⭕                                                  ❌      
protected                ⭕                         ⭕                     
public                      ⭕                         ⭕                     

 

 

Interfaces

 

객체의 모양을 특정해주기 위해 사용. 

아래에선 firstName 및 lastName 필드가 있는 객체를 설명하는 인터페이스를 사용한다.

// interfaces
interface Person {
firstName: string;
lastName: string;
}

 

* Type 과 Interface 의 차이?

 

Type의 용도 :
1. 특정 값이나 객체의 값에 대한 타입을 지정해줄 수 있다.
2. Type alias(타입에 대한 별명)를 만들어줄 수 있다.
3. 타입을 특정한 값을 가지도록 제한할 수 있다.

 

타입과 인터페이스의 차이점은 type 키워드는 interface 키워드에 비해서 좀 더 활용할 수 있는 것이 많다는 것이다.

(type 키워드는 다양한 목적으로 사용될 수 있음)
즉, interface는 오로지 객체의 형태를 타입스크립트에게 설명해주기 위한 용도로만 사용된다 !
interface는 위와 같이 상속의 개념을 사용할 수 있다 ! (오른쪽은 type을 이용하여 상속한 방법)
⇒ 문법 구조가 객체지향 프로그래밍의 개념을 활용 ⭐️
인터페이스의 또 다른 특징으로는 속성(Property)들을 ‘축적’시킬 수 있다는 것이다.

 

* Implements

 

implements을 사용하여 클래스가 특정 인터페이스를 충족하는지 확인할 수 있다.
클래스를 올바르게 구현하지 못하면 오류가 발생한다.
implements 절은 클래스가 인터페이스 유형으로 처리될 수 있는지 확인하는 것이다.

클래스의 유형이나 메서드는 전혀 변경하지 않는다.
또한 클래스는 여러 인터페이스를 구현할 수도 있다. 클래스 C는 A, B를 구현한다.

//implements
interface Pingable {
ping(): void;
}

// Sonar클래스는 Pingable인터페이스를 implement했기 때문에 Pingable가 가진 ping메서드를 구현해줘야 합니다.
class Sonar implements Pingable {
ping() {
console.log("ping!");
}
}

 

 

* generic 을 통한 인자 전달

interface SStorage {
[key:string]:T
}

class LocalStorage {
private storage: SStorage = {}
//Create
set(key:string, value:T){
if(this.storage[key] !== undefined){
return console.log(`${key}가 이미 존재합니다. update 호출 바랍니다.`)
}
this.storage[key] = value
}
//Read
get(key:string):T|void {
if(this.storage[key] === undefined){
return console.log(`${key}가 존재하지 않습니다.`)
}
return this.storage[key]
}
//Update
update(key:string, value:T){
if(this.storage[key] !== undefined){
this.storage[key] = value
} else {
console.log(`${key}가 존재하지 않아 새로 만듭니다.`)
this.storage[key] = value
}
}
//Delete
remove(key:string){
if(this.storage[key] === undefined){
return console.log(`${key}가 존재하지 않습니다.`)
}
delete this.storage[key]
}
clear(){
this.storage = {}
}
}

const stringsStorage = new LocalStorage()

const booleanStorage = new LocalStorage()
728x90