An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
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 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.
Original Link: https://dev.to/nickytonline/strongly-typed-json-in-typescript-5gb2
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To