Polymorphism 다형성
다형성이란?
- 다른 모양의 코드를 가질 수 있게 해주는 것
다형성을 이룰수 있는 방법은?
- 제네릭을 사용하는 것
제네릭
- 제네릭은 placeholder 타입을 쓸 수 있도록 해준다
- concrete타입이 아니라 placeholder타입이다
- 때가 되면 ts가 placeholder타입을 concrete타입으로 바꿔준다
- 즉, concrete타입을 쓸 필요가 없이 placeholder만 쓰면 된다
- 같은 코드를 다른 타입에 대해서 쓸 수 있도록 해준다
API만들기
- localstorage api와 비슷한 api 만들기
- js에서 사용한 로컬스토리지 api와 같은 api를 가지는 클래스를 만들기
⭐️⭐️⭐️중요⭐️⭐️⭐️
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("ket");
stringsStorage.set("hello", "how are you");
const booleansStorage = new LocalStorage<boolean>();
booleansStorage.get("xxx");
booleansStorage.set("hello", true);
개발자로서 배울 점이 많은 글이었습니다. 감사합니다.