Strongly Typed JSON in TypeScript
source link: https://dev.to/nickytonline/strongly-typed-json-in-typescript-5gb2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
typescript (7 Part Series)
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
}
}
Enter fullscreen mode
Exit fullscreen mode
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK