Reputation: 2132
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?
Upvotes: 29
Views: 25321
Reputation: 8745
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;
Upvotes: 3
Reputation: 1465
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
Upvotes: 27
Reputation: 327624
If you don't mind having an intermediate variable, you can do it this way:
import _data from './data.json';
const data: Data = _data;
The _data
variable is of whatever type the compiler infers for it, while the data
variable has the same value but is of the type you annotate.
Upvotes: 1