I'm working on a function that takes two objects and creates a new object with a unique set of properties. The keys from both objects are merged, but if there are common keys, the index of the object they came from is added as a suffix. I'm struggling to correctly define the return type for this function. Here's an example:
export function disjointUnion<
T extends Record<string, any>,
U extends Record<string, any>
>(obj1: T, obj2: U) {
const seenKeys = new Set<string>();
const result = {} as Record<string, any>; // Need help typing this
for (const k of Object.keys(obj1)) {
result[k] = obj1[k];
seenKeys.add(k);
}
for (const k of Object.keys(obj2)) {
if (!seenKeys.has(k)) {
result[k] = obj2[k];
continue;
}
result[k + 0] = result[k];
result[k + 1] = obj2[k];
delete result[k];
}
return result;
}
// Is there a way to type this as { job0: string; job1: string; age: number} ?
const obj3 = disjointUnion({ job: "developer", age: 30 }, { job: "teacher" }) ;