I've created a function that combines an array of keys with an array of values to form an object. Here's how the function looks:
function mergeToObject(keys: string[], values: string[]) {
const object:? = {}
for (let i = 0; i < keys.length; i++) {
object[keys[i]] = values[i] // TypeScript raises an error here
}
return object
}
To demonstrate how the function works, consider this example:
mergeToObject(['a', 'b', 'c'], ['x', 'y', 'z']) // => { a: 'x', b: 'y', c: 'z' }
I always provide the keys
parameter as a constant like ['a', 'b', 'c']
, rather than a dynamic value. Therefore, I believe there must be a generic way to specify the return type containing specific keys such as a
, b
, and c
.
For better understanding, let's look at a more concrete example:
const values = ['x', 'y', 'z']
// If I call the function like this
const object = mergeToObject(['a', 'b', 'c'], values)
// Then the type of object should be `{ a: string, b: string, c: string }`
object.a // is valid
object.b // is valid
object.c // is valid
object.d // is not valid
// Alternatively, if I call the function like this
const object = mergeToObject(['e', 'f', 'g'], values)
// Then the type of object should be `{ e: string, f: string, g: string }`
object.e // is valid
object.f // is valid
object.g // is valid
object.d // is not valid
So, what exactly would the generic syntax look like? Any guidance on this matter would be highly appreciated.