I am currently working on a function called createCells
that takes an array of strings and generates an object with properties based on the index of each item in the array.
For instance, calling createCells(['10', '12', '13'])
will produce an object with properties {Cell0, Cell1, Cell2}
.
Up to this point, I have managed to create a version of the function where the object's properties are determined by the values in the array.
const createCells = <T extends `${number}`[]>(
args: T,
) => {
return args.reduce(
(prev, curr) => ({
...prev,
[`Cell${curr}`]: () => { },
}),
{}
) as {
[key in typeof args[number] as `Cell${key}`]: (
) => void;
};
};
However, using this implementation, the function createCells(['10', '12', '13'])
would result in an object with properties {Cell10, Cell12, Cell13}
.
To achieve my desired outcome, the function should be modified as follows:
const createCells = <T extends `${number}`[]>(
args: T,
) => {
return args.reduce(
(prev, _curr, index) => ({
...prev,
[`Cell${index}`]: () => { },
}),
{}
)
};
My question is how can I use TypeScript to specify the type of the object returned by this function?