TypeScript:将输入类型T映射到树形类型

时间:2020-09-18 08:59:08

标签: typescript typescript-typings

这是Interface Depending on the Types of a Recursive Property

的后续活动

很抱歉,如果它看起来像是“编写我的代码”的问题,那肯定不是那样的!我刚开始使用高级类型输入,但发现很难掌握表达类型的可能性。所以请忍受我:)

在我的代码中,我想将一个对象转换为树形结构。该代码已经在执行此操作,但是我希望这些类型能够正确地反映出来。该代码遍历对象的每个属性(如果为数组,则遍历项目),并将它们变成节点。

See Stackblitz for detailed example

我目前的做法:

interface Node<Type, Children> {
  value: Type,
  children: Children[],
}

function treeOf<T>(
  value: T,
): Node<
  T,
  {
    [K in T]: Node<T[K], any[]>[]
  },
> 

...给我一个TypeScript错误:

Type 'Node<{ [x: string]: T[any]; }, any[]>' does not satisfy the constraint 'Node<unknown, any[]>[]'.
  Type 'Node<{ [x: string]: T[any]; }, any[]>' is missing the following properties from type 'Node<unknown, any[]>[]': length, pop, push, concat, and 26 more.

...而且我认为它也不能正确处理数组,因为它考虑的是数组的属性(“ push”,“ pop”,...)而不是其项目。

我也尝试过

function treeOf<T>(
  value: T,
): Node<
  T,
  Node<
    {
      [K in T]: T[K];
    },
    any[]
  >
> {

...但无济于事。

同样,我不知道TypeScript是否也可以做到这一点,或者我现在是否要求更多。但是也许有人可以告诉我:)

Stackbitz

https://stackblitz.com/edit/typescript-gb9bco?file=index.ts

0 个答案:

没有答案