I created a function that takes an array and returns an object by setting keys using the values from the array.
Here's a simplified example:
// The input 'arr' will be an array of arrays containing either one or two strings
function createObject(arr) {
const output = {}
arr.forEach(value => {
// If there are two strings in the array, use the second one as the key
const key = value.length === 1 ? value[0] : value[1]
// Always use the first string as the value
const val = value[0]
output[key] = val
})
return output
}
For example, calling
createObject([['a', 'orange'], ['b'], ['c', 'apple'])
will result in { orange: 'a', b: 'b', apple: 'c' }
with type { orange: string, b: string, apple: string }
, which we'll refer to as type R
. Please note that I am not concerned about the values of R
being literals. Using the more general string
type is sufficient for my needs.
In Typescript, I aim to infer the return type R
based on a generic input T
.
I can define T
like this:
function createObject<T extends Array<[string, string?]>(arr: T) { ... }
Is it possible to derive R
from T
?
Update
An issue I foresee when trying to achieve this in Typescript is that R
would need to consider the order of values in
T</code, which could lead to duplicate keys.</p>
<p>This challenge deviates from the simpler generic object type -> generic object type mapping syntax <code>[K in keyof T]: T[K] extends Thing ? ... : ...
.
If this proves to be problematic, but there is a potential workaround to handle it only in cases where there are no duplicate keys, that approach would suffice for my requirements.