Strongly Typed JSON in TypeScript

Strongly Typed JSON in TypeScript

Someone in one of the Slack communities I'm a part of asked today how to type JSON in TypeScript, specifically importing JSON and then typing it. They wondered if casting the JSON to unknown and then casting to a known type when consumed was a good approach.

The solution is not that complicated. We need to get our hands a little dirty and dig into the TypeScript compiler options for our project.

By default, if you import JSON, TypeScript will mention that it can't import it with the following error message:

Cannot find module './data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.ts(2732)

So TypeScript tells us what to do. Add the --resolveJsonModule flag. This is helpful if we're running the TypeScript CLI, but that is not what we're doing. What needs to be done is to add the resolveJsonModule key to the compiler options in the tsconfig.json file and set it to true.

{
  "compilerOptions": {
    "resolveJsonModule": true,
    // more awesome compiler options
  }
}

Once that's done, you'll notice that if you type data., we have fully typed JSON data.

data variable in VS Code displaying autocomplete with properties of the data object

This is great for using data in a typed manner, but what if we needed the JSON type elsewhere in the project? We can create a type for it using typeof.

type PersonalInfo = typeof data;

The type PersonalInfo displaying its shape in CodeSandbox

You can play around with this CodeSandbox and have some fun seeing it all in action.