How to Import a JSON File in TypeScript

Here’s a step-by-step guide to importing a json file TypeScript:

Step 1: Enable JSON Imports in TypeScript Configuration

Ensure that you have the following setting in your tsconfig.json:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}
  1. “resolveJsonModule”: true: It allows TypeScript to understand JSON imports.
  2. “esModuleInterop”: true: It ensures compatibility between CommonJS and ES modules.
  3. “moduleResolution”: “node”: It instructs TypeScript to use the Node.js style of module resolution.

Step 2: Importing the JSON file

Suppose you have a JSON file named data.json that looks like this:

{
  "name": "John",
  "age": 30
}

You can import and use this JSON file in a TypeScript file like so:

import * as data from './data.json';

console.log(data.name);
console.log(data.age);

Output

John
30

Optional step: Type Safety

If you want type safety for your JSON data, you can define an interface in TypeScript and ensure that the JSON conforms to that interface

interface Person {
  name: string;
  age: number;
}
 
 import * as data from './data.json';
 
 const person: Person = data;
 
 console.log(person.name);
 console.log(person.age);

Output

John
30

This way, if the structure of the JSON file changes in a way that does not match the Person interface, you will get a compile-time error.

That’s it! We’ve successfully imported a JSON file in TypeScript. Remember to ensure your build process, such as Webpack or Rollup, supports JSON imports if you’re using one.

Related posts

Read a JSON File in TypeScript

Read a JSON file in JavaScript

Leave a Comment