I have a unique enum in conjunction with its corresponding union type.
type User = { name: string, age: number }
export enum StorageTypeNames {
User = "user",
Users = "referenceInfo",
IsVisibleSearchPanel = "searchPanel",
PropertyPanelInfo = 'propertyPanelInfo'
};
type StorageType =
| { name: StorageTypeNames.User, data: User }
| { name: StorageTypeNames.Users, data?: User[] }
| { name: StorageTypeNames.IsVisibleSearchPanel, data?: boolean }
| { name: StorageTypeNames.PropertyPanelInfo, data: {visibility: boolean};
Within a class utilizing these types, I am endeavoring to implement a generic function.
export class StorageHelper {
private static readonly _storage = window.localStorage;
static get<T>(type: StorageType): T;
static get<T>(type: StorageTypeNames): Pick<StorageType, 'data'>;
static get<T>(type: StorageType | StorageTypeNames): T {
let data: string | null = null;
if(typeof type === 'string')
data = this._storage.getItem(type);
else
data = this._storage.getItem(type.name);
return data ? JSON.parse(data) : null;
}
}
The objective is to achieve the following outcome: depending on the input parameter type, TypeScript should suggest the properties of the output object.
const userData = StorageHelper.get(StorageTypeNames.User).data. //TypeScript assistance is not available
https://i.sstatic.net/y57rt.png
Could you provide guidance on how to accomplish this? Thank you in advance