扩展嵌套对象的通用类型

时间:2021-06-02 16:15:58

标签: typescript typescript-typings typescript-generics

我想为接口的记录动态设置一个类型。

interface ChildInput<V> = {value: V};

现在,我想记录不同的 ChildInput<V>。 所以,ParentInput 看起来像这样:

interface ParentInput<Keys extends string, T> /*this is the point of the question*/ = {
  [index: Keys]: ChildInput<?> /*this is the point of the question*/
}

例如:

const parentInput =  {
  foo: {value: 2},
  bar: {value: 'bar'},
  foobar: {value: true},
  .
  .
  .
}

parentInput 的预期结果应该是这样的:

interface ParentInput {
  foo: ChildInput<number>,
  bar: ChildInput<string>,
  foobar: ChildInput<boolean>,
}

ChildInput 变量中具有 parentInput 类型的键的数量未知。也是值的类型。 我想找到一种方法,给定变量,动态键入 parentInput 的正确类型的 ChildInput

这个问题对我来说很难表述和解释。请写信以获得更多说明。

1 个答案:

答案 0 :(得分:0)

这里的关键问题是您需要从名称/键映射到类型。做到这一点的唯一方法是使用完全定义的对象类型文字或接口。因此,我们可以提供一个更简单的接口作为通用输入,然后使用映射类型将其转换为结果形状。

interface ChildInput<T> {
    value: T
}

type ParentInput<T> = {
    [K in keyof T]: ChildInput<T[K]>
}

type Example = ParentInput<{
    foo: number,
    bar: string,
    foobar: boolean
}>

// Example will be
// {
//   foo: ChildInput<number>,
//   bar: ChildInput<string>,
//   foobar: ChildInput<boolean>,
// }

这可能仅在 ChildInput 更复杂或您在许多类型中使用此映射以节省更多冗余时才有用。