Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing JSON as a type

Tags:

typescript

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?

like image 804
RedHatter Avatar asked Sep 05 '25 03:09

RedHatter


2 Answers

I can think of 3 main ways here:

  1. You can use a require with a type assertion like so:
const data: Data = require('./data.json')
  1. You can continue to import, but use an additional variable (typed) like so:
import untypedData from './data.json'

const data: Data = untypedData
  1. You can add a module typings file and add this to the 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

like image 171
g2jose Avatar answered Sep 07 '25 19:09

g2jose


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;
like image 37
Top-Master Avatar answered Sep 07 '25 20:09

Top-Master