【问题标题】:Is there a common (not any) type in typescript for [] and LinkedList<>/Dictionary<>[] 和 LinkedList<>/Dictionary<> 的打字稿中是否有通用(不是任何)类型
【发布时间】:2014-06-09 00:05:39
【问题描述】:

我们必须在 web worker 和主应用程序之间复制对象。我们已经建立了一个系统,在该系统中,对于复制的每个类,我们定义一个接口,然后定义一个实现该接口的类。

这很有效,因为复制的 JSON 可以转换为接口,然后可以分配属性。让类实现接口并不重要,但它很干净并且可能会减少错误。

但是我们有一个问题。我们使用typescript-collections 类。所以我的班级会有:

export class DocHeader {

    public format:DocumentFormat;
    public fonts : collections.LinkedList<fonts.FontAttributes>;
    public styles : collections.Dictionary<string, styles.Style>;

但 JSON 是一个数组,因此将是:

export interface IDocHeader {

    format:DocumentFormat;
    fonts : fonts.FontAttributes[];
    styles : styles.Style[];
}

我知道答案可能是“不,不可能”。但我认为问永远不会有坏处。是否有某种类型(而不是任何类型),例如 IEnumerable,至少我可以在匹配这两种用途的界面中使用?

【问题讨论】:

  • 我不明白您在寻找什么? Dictionary&lt;string, Style&gt;Style[] 实际上没有任何共同之处。你不能用一个做任何你也可以用另一个做的事情。
  • @RyanCavanaugh - 正确。在 C# 中,即使使用字典,我也可以使用 IEnumerable 来完成这项工作。但是我认为在javascript中,由于定义的JSON是一个数组,所以没有办法。
  • Dictionaryany 匹配的可能性比它与数组匹配的要好。数据很可能存储为Dictionary 内的关联数组。
  • 你考虑过IDictionary&lt;k, v&gt;的接口吗?
  • @WiredPrairie - 界面真是个好主意。我想我会试试的。谢谢。

标签: json collections typescript


【解决方案1】:

您要查找的 JSON 类型是关联数组:

export interface IDocHeader {
    format: DocumentFormat;
    fonts: fonts.FontAttributes[];
    styles: { [styleId: string]: styles.Style; };
}

【讨论】:

    猜你喜欢
    • 2023-02-08
    • 1970-01-01
    • 2020-11-16
    • 2020-04-04
    • 1970-01-01
    • 2017-03-03
    • 2023-03-23
    • 2011-07-11
    • 2023-03-17
    相关资源
    最近更新 更多