I've written a function called getParameters
that can take either an array of parameter names or an object as input. The purpose of this function is to fetch parameter values based on the provided parameter names and return them in a key-value object format where the key represents the parameter name and the value is a string type.
Here's how the function looks along with an example of its usage:
async function getParameters<T extends Array<string> | RecursiveObject>(
paramNames: T,
): Promise<ParamValuesDictionary> {
const paramNamesArr = !Array.isArray(paramNames)
? toFlatArray(paramNames)
: paramNames as Array<string>;
// Stub implementation of loading parameters
const loadedParams: Parameter[] = paramNamesArr.map(name => ({
name: name,
val: `${name}_val`,
}));
const paramValues = convertToDictionary(loadedParams);
return paramValues;
}
function toFlatArray(obj: RecursiveObject): string[] {
let values: string[] = [];
for (const value of Object.values(obj)) {
if (typeof value === 'object') {
values = values.concat(toFlatArray(value));
} else {
values.push(value);
}
}
return values;
}
function convertToDictionary(
parameters: Parameter[],
): ParamValuesDictionary {
const paramValues: ParamValuesDictionary = parameters.reduce(
(acc, { name, val }) => {
acc[name] = val;
return acc;
},
{} as ParamValuesDictionary,
);
return paramValues;
}
type Parameter = {
name: string;
val: string;
};
type RecursiveObject = {
[key: string]: string | RecursiveObject;
};
type ParamValuesDictionary = { [name: string]: string };
getParameters(['a', 'b']).then(parameters => {
console.log('Using an array:', parameters);
/* OUTPUT:
"Using an array:", {
"a": "a_val",
"b": "b_val"
}
*/
});
getParameters({
nameA: 'a',
nameB: 'b',
namesC: {
nameC1: 'c1',
nameC2: 'c2',
},
}).then(parameters => {
console.log('Using an object:', parameters);
/* OUTPUT:
"Using an object:", {
"a": "a_val",
"b": "b_val",
"c1": "c1_val",
"c2": "c2_val"
}
*/
});
The current result of the getParameters
function is a ParamValuesDictionary
, which allows any string as a key. I would like to have strict keys in the ParamValuesDictionary
based on the provided paramNames
function argument. How can I modify the type ParamValuesDictionary
to achieve this behavior? Appreciate any guidance.