포시코딩

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(5) - Polymorphism, Generic 본문

JavaScript

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(5) - Polymorphism, Generic

포시 2023. 1. 22. 22:32
728x90

다형성 (Polymorphism)

다른 모양의 코드를 가질 수 있게 해준다.

다형성을 이룰 수 있는 방법은 제네릭을 사용하는 것이다.

 

제네릭 (Generic)

제네릭은 placeholder 타입을 쓸 수 있도록 해준다. (concrete 타입 x)

때가 되면 TypeScript가 알아서 placeholder 타입을 concrete 타입으로 바꿔준다.

 

예시

polymorphism, generic, class, interface를 다 합쳐서 작업해보자

localStorage와 비슷한 기능을 만들어볼거임

 

우선

interface Storage {
    
}

이렇게 작성하면 

잘 알고 있는 JavaScript의 web storage API를 위한 인터페이스가 이미 있다는 것을 알 수 있다.

이 상태에서 property를 작성하면

이전 포스팅에서 해봤듯 Storage에 새 property를 추가하는 오버라이드(override)를 하게된다. 

그러니 이름을 변경해서 사용

 

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.get('x');
stringsStorage.set('hello', 'how are you')

const booleansStorage = new LocalStorage<boolean>();

booleansStorage.get('y');
booleansStorage.set('hello', true)

Generic 때문에 value의 type이 변하는걸 확인할 수 있다.

728x90