Html_css_js
TS - generic인자로 다형성 구현
rhanziy
2022. 11. 1. 14:58
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("key")
stringsStorage.set("hello", "how are you")
const booleanStorage = new LocalStorage<boolean>()
booleanStorage.get("xxx")
booleanStorage.set("hello", true)
같은 클래스에 generic 타입을 지정해 전달하면서 각각 다른 타입의 메소드 입출력 가능한 코드
인터페이스, 클래스등에 제네릭 인자를 전달가능