My goal is to create a function that can dynamically add fields and functions to an object based on arguments provided. However, I'm encountering an issue where the function does not recognize the types of these dynamic fields. Here's a simple example that illustrates the problem:
type Extended<Base extends object, Name extends string> =
Base & Record<Name, string> & Record<`${Name}Something`, boolean>;
const addFields = <Base extends object, Name extends string>(
obj: Base, names: ReadonlyArray<Name>
): Extended<Base, Name> => {
return names.reduce((acc, name) => {
acc[name] = "test"; // error!
//~~~~~~~
// Type 'string' is not assignable to type 'Extended<Base, Name>[Name]'.(2322)
acc[`${name}Something`] = true; // error!
//~~~~~~~~~~~~~~~~~~~~~
// Type 'boolean' is not assignable to type
// 'Extended<Base, Name>[`${Name}Something`]'.(2322)
return acc;
}, { ...obj } as Extended<Base, Name>)
}
const test = addFields({ x: 123 }, ["y"]);
test.x;
test.y;
test.y = "test2";
test.ySomething = false;
Is there a way to make TypeScript recognize these dynamic fields within the function properly, or should I approach typing it differently to avoid this issue while still maintaining type safety?