I am currently saving settings to local storage and want to be able to input responses when retrieving (and possibly inserting) values from/to the storage.
After researching, it seems that using function overloading is the best approach. Here is what I have implemented so far:
export enum SettingsKey {
hasOnboarded = 'hasOnboarded',
phoneNumber = 'phoneNumber'
}
export async function getSetting(storage: Storage, key: SettingsKey.phoneNumber): Promise<string>
export async function getSetting(storage: Storage, key: SettingsKey.hasOnboarded): Promise<boolean>
export async function getSetting(storage: Storage, key: any) {
return storage.get(key)
}
The issue I have with this solution is the possibility of forgetting to add a new element in the enum to the overload type definitions. Is there a way to ensure all enum values are accounted for? Or perhaps a better approach altogether?
Initially, I thought this would be a simple mapping from value hasOnboarded
to return type boolean
, but clearly it's more complex than that.
It seems like conditional types could potentially solve this problem, although I'm still trying to fully grasp how they work.
Another method I came across is described in this article, but it appears to involve additional complexity.
Any insights on this matter would be greatly welcomed!