Home > Software design >  Testing JSON with typescript
Testing JSON with typescript

Time:12-22

I need to validate JSON with typescript. I wanted to do this like so:

jsonFile.json

{
  "foo": "bar",
  "fiz": "baz",
  "potato": 4
}

JSONType.ts

type JSONType = typeof jsonFile;

jsonFile2.json

{
  "foo": 5,
  "fiz": false
};

and if I do this:

const jsonFile2: JSONType = JSONFile2

I want it to throw an errors for not matching types, and a missing property.

I essentially want to make sure two JSONs have the same structure, with one of them as the source of truth. How do I do that?

CodePudding user response:

The first step is allow json modules in tsconfig.json "resolveJsonModule": true. Next step is import json files.

import file1 from './json/jsonFile.json'
import file2 from './json/jsonFile2.json'

Now, declare your type and apply it as you did.

type JSONType = typeof file1;
const jsonFile2:JSONType = file2

It should prompt this error:

Property '"potato"' is missing in type '{ foo: number; fiz: boolean; }' but required in type '{ foo: string; fiz: string; potato: number; }'.ts(2741)
jsonFile.json(4, 5): '"potato"' is declared here.
  • Related