I have written a function, which merges a keys array and a values array into an object. The implementation is just like below:
function mergeToObject(keys: string[], values: string[]) {
const object:? = {}
for (let i = 0; i < keys.length; i++) {
object[keys[i]] = values[i] // TypeScript complains it
}
return object
}
For illustrating the function, it behaves like below:
mergeToObject(['a', 'b', 'c'], ['x', 'y', 'z']) // => { a: 'x', b: 'y', c: 'z' }
And also, I always pass keys param as a constant expression like ['a', 'b', 'c'], but not a runtime value. so I guess it must exists a generic syntax exactly declaring the return type contains keys a, b and c.
For illustrating the behavior more concretely:
const values = ['x', 'y', 'z']
// If I invoke as
const object = mergeToObject(['a', 'b', 'c'], values)
// Then the type of object should be `{ a: string, b: string, c: string }`
object.a // is ok
object.b // is ok
object.c // is ok
object.d // is not ok
// In other words, if I invoke as
const object = mergeToObject(['e', 'f', 'g'], values)
// Then the type of object should be `{ e: string, f: string, g: string }`
object.e // is ok
object.f // is ok
object.g // is ok
object.d // is not ok
So what is exactly the generic written? I'll sincerely appreciate your help.