How do I define the type for imported json? For example
{
"things": "foo"
}
interface Data {
things: String,
another?: String
}
import data from './data.json' // Should have type Data
console.log(data.things)
console.log(data.another) // Should be allowed but undefined
The resolveJsonModule option will automatically generate types for the imported JSON but it is incomplete as the JSON may not contain all the possible fields for the data.
How do I define the type myself?
I can think of 3 main ways here:
require with a type assertion like so:const data: Data = require('./data.json')
import, but use an additional variable (typed) like so:import untypedData from './data.json'
const data: Data = untypedData
typeRoots part of your tsconfig.json like so:// File data.d.ts
declare module "data.json" {
things: String,
another?: String
}
// File tsconfig.json
{
...
"typeRoots": [
"/*path to data.d.ts*/"
]
}
This will let you import along with having the imported item typed correctly
See also Importing json file in TypeScript
Update 2022;
If you don't need fancy types, like String|null|false, then the compiler can infer the type:
First, enable related option in tsconfig.json file, like:
{
"compilerOptions": {
...
"resolveJsonModule": true,
}
}
Then simply import, and use typeof keyword, like:
import myJsonObject from './my-file.json';
export type MyType = typeof myJsonObject;
Note that you don't need to define and export type, and could instead directly use as type, like:
let myVariable: typeof myJsonObject;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With