I'm working with a simple function that can handle either a single object of type T
or an array of objects of type T[]
. It processes the input and returns results corresponding to the type provided. For instance, if an array is passed in, an array of results will be returned; if a single item is passed in, a single result will be returned.
The transpiled JavaScript functions as expected, but I am running into issues with the type system. It keeps insisting on nesting the array inside the generic instead of resolving it as desired. I'm not sure why this is happening or how to make sure it resolves correctly.
Example Function
- Playground Example
type OneOrMany<T> = T | T[]
type Item = Record<string, any>
type CapitalizedProps<T extends Item> = {
[K in keyof T as Capitalize<K & string>]: T[K]
}
function toCapitalizedProps<T extends Item>(item: T): CapitalizedProps<T>
function toCapitalizedProps<T extends Item>(items: T[]): CapitalizedProps<T>[]
function toCapitalizedProps<T extends Item>(
itemOrItems: OneOrMany<T>,
): OneOrMany<CapitalizedProps<T>> {
if (Array.isArray(itemOrItems)) {
return itemOrItems.map((item) =>
toCapitalizedProps(item),
) as CapitalizedProps<T>[]
}
const result = { ...itemOrItems }
for (const key in result) {
result[(key[0].toUpperCase() + key.slice(1)) as keyof T] = result[key]
delete result[key]
}
return result as unknown as CapitalizedProps<T>
}