'Importing JSON as a type
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?
Solution 1:[1]
I can think of 3 main ways here:
- You can use a
require
with a type assertion like so:
const data: Data = require('./data.json')
- You can continue to
import
, but use an additional variable (typed) like so:
import untypedData from './data.json'
const data: Data = untypedData
- You can add a module typings file and add this to the
typeRoots
part of yourtsconfig.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
Solution 2:[2]
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.
Solution 3:[3]
Update 2022;
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | jcalz |
Solution 3 | Top-Master |