Front-end/타입스크립트로 블록체인 만들기

[TS] Polymorphism + Generic Type + Interface

탱 'ㅅ' 2024. 1. 4. 12:39
// Storage는 이미 JS내 존재하여 재선언이 됨
interface SStorage<T> {
	[key:string]: T
}

class LocalStorage<T> {
	// 초기화할 것이 없기 때문에 constructor 사용하지 않음 
	private storage: SStorage<T> = {}
    
    set(key: string, value: T) {
    	if (this.storage[key] === undefined) {
	    	this.storage[key] = value    
        }
    }
    get(key: string): T {
    	if (this.storage[key] !== undefined) {
	    	return this.storage[key]
        }
    }
    remove(key: string) {
    	if (this.storage[key] === undefined) {
	    	delete this.storage[key]
        }
    }
    clear() {
    	this.storage = {}
    }
}

const stringsStorage = new LocalStorage<string>()
stringsStorage.get("key") // return string
stringsStorage.set("hello", "hi") // value: string

const booleansStorage = new LocalStorage<boolean>()
booleansStroage.get("xxx") // return boolean
boolenasStroage.set("xxx", true) // value: boolean

'Front-end > 타입스크립트로 블록체인 만들기' 카테고리의 다른 글

[TS] simple blockchain  (0) 2024.01.08
[TS] tsconfig.json  (0) 2024.01.04
[TS] Interfaces  (1) 2024.01.02
[TS] Classes  (1) 2024.01.02
[TS] HW - Polymorphism, Generic Type  (1) 2023.12.21