I want to create a function that accepts two arguments, the first is an object that includes an array of strings that are the required fields for the second argument. e.g
const configOptions = {
config1: {
value: string,
props: ['firstProp', 'secondProp']
}
};
myFunc(configOptions.config1, {
'firstProp': 'first value', // <-- firstProp and secondProp are required because they are defined in config.props
'secondProp': 'second value',
});
I can achieve this by referencing the specific config in the function declaration and doing a const assertion on the config options
const configOptions = {
config1: {
value: 'a string value',
props: ['firstProp', 'secondProp']
}
} as const;
function myFunc<T extends typeof configOptions.config1>(
option: T,
params: { [key in typeof option.props[number]]: string }
) {}
myFunc(configOptions.config1, {
firstProp: 'first value',
secondProp: 'second value',
});
But I want to achieve this more generically so I could call the same function and use one of many configs. Is this possible?
Here is a stackblitz https://stackblitz.com/edit/typescript-ydyt4v