如何将JSON转换为DefinitelyTyped类型?

如何将JSON转换为DefinitelyTyped类型?

问题描述:

我正在创建一些测试数据,并且不想通过手动编写我的类型化测试对象的麻烦 - 我宁愿提供JSON并将其投射到我的案例中的DefinitelyTyped对象数组。我怎样才能做到这一点?如何将JSON转换为DefinitelyTyped类型?

我试着做以下,但它仍然是回来为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将打字稿被输入到fhir.BundleEntry[]。在运行时它仍然是对象。在Typescript中铸造只会告诉编译器,您知道该对象的sape将与您要投射到的类相同。

你的问题是,我不认为你提供的json字符串符合你投的类型,它似乎有以下形状{ entry:fhir.BundleEntry[] }(假设条目中的元素与fhir.BundleEntry。so你应该像这样猫:

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