【问题标题】:Describe deeply nested object function result in Typescript在 Typescript 中描述深度嵌套的对象函数结果
【发布时间】:2017-05-25 14:54:31
【问题描述】:

我有一个满足以下条件的函数:

1) 它使用一个对象,可以有任何级别的嵌套,比如 Redux 的 State。在嵌套结束时,它有一些类实例,我们称之为Leaf。因此,示例对象类型可能如下所示:

type Sample = {
  nested1: {
    nested2: Leaf,
  },
  nonesting: Leaf
}

或者,它可能看起来像这样:

type Sample2 = {
  nested1: {
    nested2: {
      nested3: {
        nested4: Leaf
      }
    },
    nested5: {
      nested6: {
        nested7: Leaf
      }
    }
  },
  nested8: {
    nested9: Leaf
  }
}

就像 Redux 的 State 一样,没关系。这取决于图书馆用户。

2) 它返回一个与输入对象具有完全相同结构的对象,但该对象中的所有Leaf 都被替换为ProcessedLeaf。

我希望能够访问该对象的ProcessedLeaf,如下所示:

result.nested1.nested2

当前状态

这是我探索的结果:

interface InputObject {
  [key: string]: InputObject | Leaf
}

interface OutputObject {
  [key: string]: OutputObject | ProcessedLeaf
}

function process(input: InputObject): OutputObject;

但是,当我尝试使用点符号访问对象时,出现错误:

TS2339:Property 'nested2' does not exist on type 'ProcessedLeaf | OutputObject'.
Property 'nested2' does not exist on type 'ProcessedLeaf'.

另一个尝试:

interface InputObject {
  [key: string]: InputObject | Leaf
}

type OutputObject<T> = {
  [key in keyof T]: OutputObject<T[key]> | ProcessedLeaf
}

function process<T extends InputObject>(input: T): OutputObject<T>;

但是,错误类似:

TS2339:Property 'nested2' does not exist on type 'ProcessedLeaf | OutputObject<{ nested2: Leaf; }>'.
Property 'nested2' does not exist on type 'ProcessedLeaf'.

我知道有一种方法可以通过以下方式调用元素:

result['nested1']['nested2']

但它没有任何利润。我可以从函数中返回any,它会是一样的。

是否可以使用当前的打字稿创建这种类型?

【问题讨论】:

  • 可能要等到this issue才能解决。
  • @kimamula,是的,这正是我一直在寻找的。你能把它写成答案吗?

标签: typescript


【解决方案1】:

目前,似乎没有办法实现您想要做的事情。 解决了this issue,或许你应该可以写出类似下面的东西。

type Tree<T, Leaf> = {
  [K in keyof T]: T[K] extends Leaf ? Leaf : Tree<T[K], Leaf>;
};
type ProcessedTree<T, Leaf, ProcessedLeaf> = {
  [K in keyof T]: T[K] extends Leaf ? ProcessedLeaf : ProcessedTree<T[K], Leaf, ProcessedLeaf>;
};

function process<T>(input: Tree<T, Leaf>): ProcessedTree<T, Leaf, ProcessedLeaf>;

【讨论】:

    【解决方案2】:

    是否可以使用当前的打字稿创建这种类型?

    没有。由于您明确希望允许任何点,例如a.b.c 是 Nested 或 Leaf 任何真实的类型定义都会有这个联合。有关如何克服您遇到的额外错误的更多文档:Generic TypeScript interface with mixed member types。

    解决方案

    我会重新考虑 什么是嵌套的,什么不是在 TypeStyle 中查看$nest:http://typestyle.io/#/core/concept-interpolation

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 2020-04-19
      • 2020-02-15
      • 1970-01-01
      • 2017-04-04
      • 2019-03-15
      • 1970-01-01
      • 2015-09-15
      • 2020-12-18
      相关资源
      最近更新 更多