我想要实现的是根据“rest”参数中提供的参数数量键入一个深度嵌套的函数 ReturnType。例如,如果我们有:
getFormattedDates(
dates: Date[],
...rest: string[] // ['AAA', 'BBB', 'CCC', etc...]
): Record<string, Record<string, Record<string,etc...>>>
最后一个嵌套对象的类型应为 Record<string, Date[]>
,而如果没有第二个参数,则返回类型应为 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[]>>>
关于typescript - 在 returnType 中获取与传递给函数的参数一样多的嵌套记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70379893/