如何将 JSON 转换为 DefinitelyTyped 类型?

How to cast JSON to a DefinitelyTyped type?

我正在创建一些测试数据,不想经历手动写出我输入的测试对象的麻烦 - 我宁愿提供 JSON 并将其转换为 DefinitelyTyped object - 在我的例子中是数组。我怎样才能做到这一点?

我正在尝试执行以下操作,但它仍然以 Object:

的形式返回
const outputData = <fhir.BundleEntry[]>JSON.parse(`{"entry": [
  {
    "fullUrl": "https://vonk.furore.com/Patient/1",
    "resource": {
      "resourceType": "Patient",
      "id": "1",
      "meta": {
        "versionId": "b345396d-f3b6-46ce-8ceb-0b5c0dafab2e",
        "lastUpdated": "2017-06-20T07:28:54.979+00:00"
      },
      "identifier": [
        {
          "type": {
            "coding": [
              {
                "system": "http://hl7.org/fhir/v2/0203",
                "code": "SS"
              }
            ]
          },
          "system": "https://github.com/projectcypress/cypress/patient",
          "value": "577492"
        }
      ],
      "active": true,
      "name": [
        {
          "use": "official",
          "family": "Copeland",
          "given": [
            "Brian"
          ]
        }
      ],
      "gender": "male",
      "birthDate": "1949-03-15",
      "managingOrganization": {
        "reference": "Organization/1"
      }
    },
    "search": {
      "mode": "match"
    }
  }
]}`);

outputData 将在 Typescript 中输入为 fhir.BundleEntry[]。在运行时它仍然是对象。在 Typescript 中转换仅告诉编译器您知道对象的 sape 将与您转换到的 class 相同。

你的问题是我认为你在那里提供的 json 字符串不符合你强制转换的类型,它似乎具有以下形状 { entry:fhir.BundleEntry[] } (假设元素在条目的形状与 fhir.BundleEntry 相同,所以你应该像这样的猫:

const outputData = <{ entry:fhir.BundleEntry[] }> JSON.parse('{ .. }')