I am facing a challenge with merging objects in an array. Here is an example of what I am working with:
const objectArray = {
defaults: {
size: {
foo: 12,
bar: {
default: 12,
active: 12
}
},
color: {}
}
}
In addition, I have another object as follows:
const customObject = {
size: {
m: '12px'
}
}
The goal is to merge the contents of objectArray.defaults.size
into customObject.size.components
.
Even though the logic for this merge is straightforward, TypeScript cannot infer the output. To address this, I manually defined the ReturnType using mapped types in TypeScript as shown below:
const mergeObjects = <
T extends RawTheme,
D extends ThemeDependency[] = ThemeDependency[],
A extends number = number
>(
dependencies: D,
options?: MergeOptions
): T & {
size: T['size'] & {
components?: {
[Key in KeysOfUnion<
D[A]['defaults']['size']
>]: D[A]['defaults']['size'][Key]
}
}
}
However, I encountered an issue where I was unable to access the value of a specific object by its index within the array. The value of size.components.bar
ended up being unknown
.
I am seeking suggestions on how to properly resolve this dilemma. Any insights would be greatly appreciated.
For those interested, here is the KeysOfUnion Type reference:
type KeysOfUnion<T> = T extends T ? keyof T : never