본문 바로가기
front-end/TypeScript

[TS]08 제네릭+다형성+클래스+인터페이스

by -제이리 2022. 5. 17.
728x90
320x100
다형성: 다른모양의 코드를 가질수 있게 해준다.
다형성을 이루 수 있는 방법은 제네릭을 사용하는 것이다. 제네릭은 placehoder타입을 쓸 수 있도록 해준다.
 
예시-모든타입에 쓸 수 있는 로컬스토리지 API 시뮬레이션
 
interface SStorage<T> { // Storage는 이미 내장되어 있는것이기 때문에 사용하게 되면 override가된다 그렇기 때문에 SStorage라고 할것임.
  [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>() // <string>으로 지정해주면 ts가 콜시그니처를 string으로 인식 
stringsStorage.get('key') // 마우스 올려보면 string을 받는것을 볼수있다
stringsStorage.set('hi', 'good')

const booleanStorage = new LocalStorage<boolean>();
booleanStorage.get('xx') // 마우스 올려보면 boolean을 받는것을 볼수있다
booleanStorage.set('hi', false)
728x90
320x100

'front-end > TypeScript' 카테고리의 다른 글

[TS]07 type과 interface  (0) 2022.05.16
[TS]06 클래스 / 추상클래스  (0) 2022.05.12
[TS]05 다형성 / 제네릭  (0) 2022.05.11
[TS]04 call Signatures / overloading(오버로딩)  (0) 2022.05.10
[TS]03 unKnown / void / never  (0) 2022.05.10

댓글