Resolving JSON Modules for Fun and Profit
So, you want to import some JSON from a module using TypeScript and you want the structure to determine your contracts.
At first blush, TypeScript makes it very easy to import a JSON structure with some compilerOptions
...
"compilerOptions": {
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
...
}
...
This then allows you to import a JSON file directly and get it back as an object with types all the way down.
import ProfileData from "../data/profile.json";
It works great with autocomplete and IntelliSense down to nested arrays and objects.
It is, however, readonly. None of the properties inferred from resolveJsonModule have getters, can be changed directly nor can the object be extended.
You can, however, cast the object to an interface and get the best of both worlds.