I have a JS constructor function written in Typescript and i access this constructor function from other code like this
const ls = new LocalStorage<ICountryHolidayData>()
let strdVal = ls.getItem(constants.localStorageKey).storedValue
Though the code works fine but i do not get any intellisense..neither for ls.getItem nor for the storedValue property.
I think its because constructor functions can’t inherit interface like classes do in typescript?
Otherwise can some help me understand how to do this, so that i can get intellisense for both values.
export interface ILocalStorgaeReturnValue<Type>{
storedValue: Type,
date: Date
}
export interface ILocalStorage<Type extends {}>{
setItem(key:string,value:Type):void;
getItem(key:string):ILocalStorgaeReturnValue<Type>;
removeItem(key:string ):void;
//clear();
}
export function LocalStorage<Type>(){
if( !window.localStorage)
throw new Error(`Browser does not support local storage`)
this.setItem = (key:string, val:Type ) =>{
if(!key || !val )
throw new Error(`key or value can not be null `)
const completeObj = {
storedValue: {
...val
},
date:new Date()
}
window.localStorage.setItem(key ,JSON.stringify(completeObj))
},
this.getItem = (key:string):ILocalStorgaeReturnValue<Type> =>{
if(!key )
throw new Error(`[key can not be null `)
const val= JSON.parse(window.localStorage.getItem(key))
if(!val || Object.keys(val).length<2)
return null
else
return <ILocalStorgaeReturnValue<Type>> {
...val
}
},
this.removeItem = (key:string) =>{
if(!key )
throw new Error(`Key is empty`)
window.localStorage.removeItem(key)
}
}