1

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?

3
  • Take a look at JSON Schema Commented Dec 21, 2021 at 16:58
  • This is interesting, but unfortunately not what I'm looking for Commented Dec 21, 2021 at 17:05
  • You can't do it if it's JSON. Types only exist at compile-time, and by definition JSON is parsed from a string into a data structure at run-time. If you can convert it from JSON to actual Typescript code then you can do it, for instance the answer below has a way to tell the compiler to treat it as TS code, but anything you want to get the typeof (in the Typescript sense) has to be knowable at compile-time. Commented Dec 21, 2021 at 17:11

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Can you put it in a codepen or smth like this? I believe I have this exact setup, and it doesn't throw anything
Never mind! It works
You're welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.