泛型和数组:为什么我最终会得到 `Generic<T[]>` 而不是 `Generic<T>[]`?

问题描述 投票:0回答:1

我有一个简单的函数,可以接受

T
类型的单个对象或
T[]
类型的对象数组。然后它将执行其操作并返回与传入的类型匹配的结果(即,如果传递数组,则返回结果数组,如果传递单个项目,则返回单个结果)。

转译的 JS 功能完全符合预期,但类型系统一直坚持将数组嵌套在泛型中,我不确定为什么或如何确保它解析为我想要的。

示例功能

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>
}
javascript typescript typescript-typings typescript-generics
1个回答
0
投票

覆盖按照定义的顺序进行匹配。

如果您颠倒该顺序,它可以解决您的问题:

function toCapitalizedProps<T extends Item>(items: T[]): CapitalizedProps<T>[]
function toCapitalizedProps<T extends Item>(item: T): CapitalizedProps<T>
function toCapitalizedProps<T extends Item>() {
...

}

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.