将字典JSON转换为Typescript模型

h4cxqtbf  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(168)

我想将以下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;
}

我不知道当键值被更改和新对象被添加时该怎么办。

4ioopgfo

4ioopgfo1#

看起来您需要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
正如您所看到的,它非常简单,根本不尝试模式匹配。

vmdwslir

vmdwslir2#

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

const data: iData = {
  "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"
      }
    }
  }
};

相关问题