Alex Ironside
Alex Ironside

Reputation: 5039

Testing JSON with typescript

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?

Upvotes: 0

Views: 762

Answers (1)

Marlon Ferri
Marlon Ferri

Reputation: 116

The first step is allowing the json modules by adding "resolveJsonModule": true to the tsconfig.json

Next step is importing the json files as following,

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

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

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

It should throw 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.

Upvotes: 3

Related Questions