그동안 했던 다형성, 제네릭, 클래스, 인터페이스를 모두 합쳐봐서 사용법에 대한 분석을 해보자잇!
interface SStorage<T> {
[key: string]: T;
}
class LocalStorage<T> {
private storage: SStorage<T> = {};
//Create
set(key: string, value: T) {
if (this.storage[key] !== undefined) {
return console.log(`${key}가 이미 존재합니다. update 호출 바랍니다.`);
}
this.storage[key] = value;
}
//Read
get(key: string): T | void {
if (this.storage[key] === undefined) {
return console.log(`${key}가 존재하지 않습니다.`);
}
return this.storage[key];
}
//Update
update(key: string, value: T) {
if (this.storage[key] !== undefined) {
this.storage[key] = value;
} else {
console.log(`${key}가 존재하지 않아 새로 만듭니다.`);
this.storage[key] = value;
}
}
//Delete
remove(key: string) {
if (this.storage[key] === undefined) {
return console.log(`${key}가 존재하지 않습니다.`);
}
delete this.storage[key];
}
clear() {
this.storage = {};
}
}
const stringsStorage = new LocalStorage();
const booleanStorage = new LocalStorage();
LocalStorage 클래스를 만듦SStorage 인터페이스를 만들어 연결T라는 제네릭 타입을 설정해 LocalStorage의 모든 메소드의 반환값에 같은 타입을 설정함key를 구현, 메소드에 연결set을 사용하면 주어진 키에 대한 값을 설정 가능. 키가 저장소에 이미 있는 경우 메시지를 기록하고 기존 값을 덮어쓰지 않음.get은 지정된 키의 값을 검색. 키가 저장소에 없으면 메시지를 기록하고 undefined를 반환.update는 지정된 키의 값을 업데이트. 키가 스토리지에 이미 존재하는 경우 기존 값을 덮어씀. 키가 없으면 메시지를 기록하고 새 키-값 쌍을 만듦.remove는 지정된 키의 키-값 쌍을 제거. 저장소에 키가 없으면 메시지를 기록하고 아무 작업도 수행하지 않음.clear는 저장소에서 모든 키-값 쌍을 제거.LocalStorage의 인스턴스 stringsStorage, booleanStorage 생성이런 식으로 하면 된다! 이게 되게 어려웠다. 타입을 적재적소에 배치하여 넣어야하는데..
특히 제네릭이 어렵긴하다. 뭔가 직관적이면서도 어디에 넣어야할지 모르겠다. 이런 것들도 문법이기에 쓰면 쓸 수록 괜찮겠지?
분석까지 해두셨는데 완벽히 이해하지 못하는 1인. 뿔소님처럼 저돌적으로 공부해야겠어요!