Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in the schema. For instance, if I call LocalStorage.get("some_number"), I want the return type to be number. Is achieving this in TypeScript even possible?
The parameter value typed as Keys works effectively for the input!
While attempting to use "type Values = LocalStorageSchema[Keys]" returns a union type of the values, which is not what I require.
Additionally, it appears that using the variable "key" in the get function for type narrowing is not achievable...
I have considered exploring generic types like LocalStorage.get(...) but that might defeat the purpose of specifying the return value type.
Any suggestions on how to approach this issue? Thank you!
type LocalStorageSchema = {
token: string;
some_string: string;
some_number: number;
};
type Keys = keyof LocalStorageSchema;
export const LocalStorage = {
get(key: Keys): any {
const data = window.localStorage.getItem(key);
//type ReturnType = ???
if (data !== null) {
return data;
}
console.error(`localStorage missing object with key ${key}`);
return null;
},
set(key: Keys, value: any) {
window.localStorage.setItem(key, value);
},
remove(key: Keys) {
window.localStorage.removeItem(key);
},
clear() {
window.localStorage.clear();
},
};