I struggle to define a good types for my use case.
Here is what I have:
One global object that represents Settings
const settings = {}
This object contains each individual menu mapped Menu title -> Menu settings.
const settings = {
menu1: {
showOneThing: true,
showAnotherThing: false,
},
menu2: {
renderThis: true,
renderThat: false,
}
}
I am trying to come up with a function that would return different properties available in the menu, based on what menu is selected. For example
const getSettings = (menuKey) => ...
const settingsForMenu1 = getSettings('menu1');
settingsForMenu1.showOneThing // intellisense and all of that
const settingsForMenu2 = getSettings('menu2');
settingsForMenu2.renderThis // property renderThis or renderThat are the only ones that should be available here
Now for some reason I seem to struggle with concept of generics. I think I need to use the concept of mapped types here, but I really can't figure out how. Would anyone be able to suggest ways to do what I am trying to do?
Thanks
CodePudding user response:
Would this work for you?
function getSettings<
K extends keyof typeof settings
>(key: K): (typeof settings)[K] {
return settings[key]
}