Issue
I am trying to use generics so that the caller can define what type they predict to get.
My code is like:
const getStoredData = async <T extends string | object>(key: typeof localStorageKeys[number]): Promise<T | null> => {
try {
// value is always returned as string
const value = await AsyncStorage.getItem(key);
if (value === null) return null;
// I want to create condition to check if T is string or not
// if T is object type then return parsed JSON, otherwise just string
return value != null ? JSON.parse(value) : null;
} catch (e) {
return null;
}
};
// I wanna achieve like below using the function above
// storedValue should be string
const storedValue = await getStoredValue<string>('someKey');
// then storedObjValue should be MyCustomType type
const storedObjValue = await getStoredValue<MyCustomType>('some_key');
Does anyone know how to achieve that?
Solution
Taking the advice from @Gonzalo, I do it like below and it seems working.
type LocalStorageType = {
user_id: string;
user_something: UserSomethingType;
};
type LocalStorageKeys = keyof LocalStorageType;
type LocalStorageValue = LocalStorageType[LocalStorageKeys];
const getStoredData = async <T extends LocalStorageValue>(
key: LocalStorageKeys,
): Promise<T | null> => {
try {
const value = await AsyncStorage.getItem(key);
if (value === null) return null;
if (key === 'user_id') return value as T;
return JSON.parse(value) as T;
} catch (e) {
return null;
}
};
This might not be optimal because there might be many if
condition as possible string values in LocalStorageType increase like below.
type LocalStorageType = {
user_id: string;
user_name: string;
user_email: string;
user_something: UserSomethingType;
some_value: CustomType;
some_value_two: CustomOneType;
};
// now I have to make at least 3 conditions(user_id, user_name, user_email) to distinguish string or custom types
If someone knows how to prevent that please let me know!
Answered By - Masa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.