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?