본문 바로가기
TypeScript

[타입스크립트] 다형성(polymorphism) 제네릭(generic) 클래스(class) 인터페이스(interface) 합치기

by 메이플 🍁 2022. 11. 20.

다형성: 다른 모양의 코드를 가질 수 있게 해주는 것 (제네릭 사용)
제네릭은 placeholder 타입을 쓸 수 있도록 해줌 (placeholder <-> concrete)
타입스크립트가 placeholder 타입을 concrete 타입으로 바꾸어줌

 

예제

브라우저에서 쓰는 로컬스토리지 API와 비슷한 API 만들고 타입만 넣어주기

// Storage is reserved word
interface SStorage<T> {
  [key:string]: T
}

class LocalStorage<T> {
  private storage: SStorage<T> = {}
  set(key:string, value:T){
    this.storage[key] = value
  }
  remove(key:string){
    delete this.storage[key]
  }
  get(key:string):T{
    return this.storage[key]
  }
  clear(){
    this.storage = {} 
  }
}

const stringsStorage = new LocalStorage<string>

stringsStorage.set('hello', 'how are you')
stringsStorage.get('key')

const booleansStorage = new LocalStorage<boolean>()

booleansStorage.set('xxx', true)
booleansStorage.get('xxx')

댓글