【问题标题】:Convert Dictionary JSON to Typescript model将字典 JSON 转换为 Typescript 模型
【发布时间】:2019-11-15 07:41:08
【问题描述】:

为了类型安全,我想将以下 json 对象转换为 Typescript 接口:


    {
      "attributes1": {
        "myKey1": {
          "myinnerKey11": {
            "value": "value 1",
            "name": "name 1"
          },
          "myinnerKey12": {
            "value": "value 1",
            "name": "name 1",
            "otherKey": "key 2"
          }
        }
      },
      "attributes2": {
        "myKey2": {
          "myinnerKey21": {
            "value": "value 1",
            "name": "name 1"
          },
          "myinnerKey22": {
            "value": "value 1",
            "name": "name 1",
            "otherKey": "key 2"
          }
        }
      }
    }

我尝试创建以下界面:


    export interface IFinalObj {
        attributes1: IAttributes1;
        attributes2: IAttributes2;
    }
    interface IMyInnerObj {
        value: string;
        name: string;
        otherKey?: string;
    }
    interface IDynamicInnerKey {
        [a: string]: IMyInnerObj
    }

    interface IAttributes1 {
        myKey1: IDynamicInnerKey;
    }
    interface IAttributes2 {
        myKey2: IDynamicInnerKey;
    }

我不确定在更改 Keys 值并添加新对象时该怎么办

【问题讨论】:

  • 在你的情况下,“期望的输出”是什么?
  • 使用这个为您生成界面的工具怎么样? json2ts.com 。此外,“但它没有返回所需的输出并且代码看起来很乱”是什么意思。接口什么都不返回,它们只是签名,在运行时,它们什么都不做。
  • 这取决于哪些属性是固定的,哪些是动态的,然后你可以为你的类做更好的类型。
  • @Atomzwieback 因为这是一个模型,所以像“attributes2”和“attributes1”这样的键正在改变,因为它可能像“abc”、“foo”这样的东西,所以当我映射到我的模型时它会中断跨度>

标签: json angular typescript


【解决方案1】:

您似乎需要Record<T1, T2> 接口,但如果您希望从数据中生成类型,那么是的,http://json2ts.com/ 是最好的工具。

我写了一个糟糕的版本并用你的模型进行了测试:

interface ITest {
  attributes1: {
    myKey1: {
      myinnerKey11: {
        value: string,
        name: string
      },
      myinnerKey12: {
        value: string,
        name: string,
        otherKey: string
      }
    }
  },
  attributes2: {
    myKey2: {
      myinnerKey21: {
        value: string,
        name: string
      },
      myinnerKey22: {
        value: string,
        name: string,
        otherKey: string
      }
    }
  }
}

你可以在这里https://json2dts.stackblitz.io/试试,源代码在https://stackblitz.com/edit/json2dts

如您所见,它非常简单,根本不尝试进行模式匹配。

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2018-07-04
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    相关资源
    最近更新 更多