Typescript - Polymorphism

Angela_Hong·2023년 8월 8일

TypeScript

목록 보기
5/6
post-thumbnail

Polymorphism 다형성

다형성이란?

  • 다른 모양의 코드를 가질 수 있게 해주는 것
    다형성을 이룰수 있는 방법은?
  • 제네릭을 사용하는 것

제네릭

  • 제네릭은 placeholder 타입을 쓸 수 있도록 해준다
  • concrete타입이 아니라 placeholder타입이다
  • 때가 되면 ts가 placeholder타입을 concrete타입으로 바꿔준다
  • 즉, concrete타입을 쓸 필요가 없이 placeholder만 쓰면 된다
  • 같은 코드를 다른 타입에 대해서 쓸 수 있도록 해준다

API만들기

  • localstorage api와 비슷한 api 만들기
  • js에서 사용한 로컬스토리지 api와 같은 api를 가지는 클래스를 만들기

⭐️⭐️⭐️중요⭐️⭐️⭐️

interface SStorage<T> {
  // key가 제한되지 않은 오브젝트를 정의하게 해준다
  [key: string]: T;
  // 인터페이스는 제네릭을 사용한다
}

// stfing, boolean, number만을 위한 locastorage를 만들것
// LocalStorage를 초기화할때 ts에게 T라는 제네릭을 받을 계획이라고 알려줄 것이다
class LocalStorage<T> {
  // 제네릭은 다른 타입에게 물려줄 수 있다는 특징이 있다
  // 클래스이름에 제네릭이 들어오지만, 인터페이스 SStorage로 보내줄 것이다
  private storage: SStorage<T> = {};
  // 1. 제네릭을 클래스로 보냄
  // 2. 클래스는 제네릭을 인터페이스로 보낸다
  // 3. 인터페이스는 제네릭을 사용한다

  // API디자인의 구현을 보여주기 위한 것
  set(key: string, value: T) {
    // get의 T에 오류가 생기는걸 해결하기 위해서 코드 구현
    // key와 value를 스토리지에 저장해주려면
    this.storage[key] = value;
  }
  // remove는 string형식의 key를 받아 이걸 로컬스토리지로부터 지운다
  remove(key: string) {
    delete this.storage[key];
  }
  // key를 받는 get 그리고 이건 T를 리턴해준다
  get(key: string): T {
    return this.storage[key];
  }
  clear() {
    this.storage = {};
  }
}

const stringsStorage = new LocalStorage<string>();
// string타입의 로컬 스토리지
// stringsStorage.get()을 쓰면 string을 보내주고, T를 받는다
// ts는 제네릭을 바탕으로 call signature을 만들어준다 get(key:string):string
// 왜? ts가 concrete타입으로 바꿔주기 때문
stringsStorage.get("ket"); // get(key:string):string
stringsStorage.set("hello", "how are you"); // set(key:string, value:string): void
// ts가 하는 것은 T인 value를 string인 value로 바꿔주는 것!!
// 왜? string이야? new LocalStorage<string> 여기서 string으로 만들었기 때문에

const booleansStorage = new LocalStorage<boolean>();
booleansStorage.get("xxx"); // get(key:string):boolean
booleansStorage.set("hello", true);

1개의 댓글

comment-user-thumbnail
2023년 8월 8일

개발자로서 배울 점이 많은 글이었습니다. 감사합니다.

답글 달기