How to cast JSON to a DefinitelyTyped type?

214 Views Asked by At

I'm creating some test data and don't want to go through the hassle of manually writing out my typed test Objects - I'd rather supply JSON and have that be cast to an DefinitelyTyped object - array in my case. How can I accomplish this?

I'm trying to do the following but it is still coming back as an 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"
    }
  }
]}`);
1

There are 1 best solutions below

0
On BEST ANSWER

outputData will be typed to fhir.BundleEntry[] in Typescript. At runtime it will still be object. Casting in Typescript only tells the compiler that you know that the sape of the object will be the same as the class you are casting to.

Your problem is that I don't think the json string you provide there conforms to the type you cast to, it seems to have the following shape { entry:fhir.BundleEntry[] } (assuming that the elements in entries have the same shape as fhir.BundleEntry. so you should cats like this:

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