This content originally appeared on DEV Community and was authored by Nick Taylor
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 just 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.
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;
You can play around with this CodeSandbox and have some fun seeing it all in action.
This content originally appeared on DEV Community and was authored by Nick Taylor
Nick Taylor | Sciencx (2022-04-01T03:36:19+00:00) Strongly Typed JSON in TypeScript. Retrieved from https://www.scien.cx/2022/04/01/strongly-typed-json-in-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.