TypeScript -12-

mh·2022년 5월 12일
0

TypeScript

목록 보기
12/17
post-thumbnail

Photo by Andres Perez on Unsplash

다형성, 제네릭, 클래스, 인터페이스 모두 써보기

  • 다형성:
    다른 모양의 코드를 가질 수 있게 해주는 것
    제네릭을 사용해 다형성을 이룰 수 있음
    제네릭은 placeholder 타입을 쓸 수 있게 해줌
    정해져있는 concrete type이 아닌 placeholder를 사용하므로, TS가 인수로 들어오는 값을 보고 타입을 추론 할 수 있게 됨 (placeholder값을 concrete type으로)
    이는 코드의 가독성은 물론 같은 코드를 다른 타입에 대해서도 쓸 수 있어 재사용성도 좋음

브라우저 로컬 스토리지 API 시뮬레이션

  • call signature 작성
  • class 생성
class LocalStorage {
    private storage
}

로컬 스토리지 클래스 생성, 특정 형태를 만들기 위해 interface 만들기

interface Storage {
	
}

Storage 인터페이스는 TS에서 이미 선언된 JS 웹스토리지 API를 위한 interface다.

즉 이런식으로 Storage에 새 property를 추가할 수 있다.
마치 기존 interface에 프로퍼티를 축적시키는 것처럼

그러나 여기선 override 시키지 않을 것이기 때문에 이름을 바꿔줌

interface MyStorage<T> { // 3.
    [key:string]:T
}

class LocalStorage<T> { // 1.
    private storage : MyStorage<T> = {} // 2.
}

class LocalStorage<T>
1. 제네릭을 클래스로 보냄

private storage : MyStorage<T> = {}
2. 클래스가 제네릭을 인터페이스로 보냄

interface MyStorage<T> { [key:string]:T }
3. 인터페이스는 <T> 제네릭을 사용

로컬스토리지의 set get remove 메소드 구현

interface MyStorage<T> {
    [key:string]:T
}

class LocalStorage<T> {
    private storage : MyStorage<T> = {}
    set(key:string, value:T) {}
    remove(key:string) {}
    get(key:string):T {}
}

interface MyStorage<T> {
    [key:string]:T
}

class LocalStorage<T> {
    private storage : MyStorage<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.get("key")
stringsStorage.set("keyname", "stringValue")

get을 사용하면 스트링 키를 보내고 :T를 return하여 받는다.
여기서 TS가 제네릭을 바탕으로 콜 시그니처를 만들어주기 때문에 이렇게 보임

받는값이 불리언일 경우

booleansStorage.get("abc")
booleansStorage.set("boolkey", true)

스트링을 주고 불리언을 받는다.

profile
🤪🤪🤪🤪🤪

0개의 댓글