typescript - 在 returnType 中获取与传递给函数的参数一样多的嵌套记录

标签 typescript function typescript-typings return-type nested-object

我想要实现的是根据“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[]>>>

Playground

关于typescript - 在 returnType 中获取与传递给函数的参数一样多的嵌套记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70379893/

相关文章:

angular - 如何为对象创建行为主题并在另一个组件上订阅它?

javascript - 使用Typescript在组件中传递参数时出错

javascript - 'if...else'没有检查任何其他条件,直接跳到最后一个 'else'语句

reactjs - redux 工具包使用 typescript 模拟商店

javascript - typescript / react : Module has no exported member

c - 在 Ida pro 中反汇编 c 函数

javascript - php 函数不将值返回给 javascript 变量

typescript - 难道真的没有办法在没有导入和导出的情况下全局声明类型吗?

Typescript:根据预期的返回类型约束函数泛型类型