在返回类型中获取与传递给函数的参数一样多的嵌套记录

Get as many nested Records in returnType as the arguments passed to the function

我想要实现的是根据“rest”参数中提供的参数数量键入函数的深度嵌套 ReturnType。例如,如果我们有:

getFormattedDates(
  dates: Date[],
  ...rest: string[] // ['AAA', 'BBB', 'CCC', etc...]
): Record<string, Record<string, Record<string,etc...>>>

最后一个嵌套对象的类型应该是Record<string, Date[]>,而如果没有第二个参数,return类型应该是Date[]

到目前为止,我已经尝试过谷歌搜索各种东西,但我无法掌握这种类型,我也想了解其背后的逻辑。

这是我问的第一个问题,所以我希望它足够明确。 :)

希望有人能阐明这个问题。谢谢!

您可以构建类型 recursively:

type ToRecord<T> = T extends [string, ...infer Rest]
    ? Record<string, ToRecord<Rest>>
    : Date[]

declare function getFormattedDates<T extends string[]>(
    dates: Date[],
    ...rest: T // ['AAA', 'BBB', 'CCC', etc...]
): ToRecord<T>

const p0 = getFormattedDates([]) // Date[]
const p1 = getFormattedDates([], 'AAA') // Record<string, Date[]>
const p3 = getFormattedDates([], 'AAA', 'BBB', 'CCC') // Record<string, Record<string, Record<string, Date[]>>>

Playground