How to Import a JSON file in TypeScript | bobbyhadz (2024)

How to Import a JSON file in TypeScript

# Import a JSON file in TypeScript

To import a JSON file in TypeScript:

  1. Set resolveJsonModule to true in your tsconfig.json file.
  2. Set esModuleInterop to true in tsconfig.json.
  3. Import the JSON file as import employee from './employee.json'.

Make sure you have set resolveJsonModule and esModuleInterop to true in your tsconfig.json file.

tsconfig.json

Copied!

{ "compilerOptions": { // ... other options "esModuleInterop": true, "resolveJsonModule": true }}

How to Import a JSON file in TypeScript | bobbyhadz (1)

The code for this article is available on GitHub

Here is the JSON file we will import into a TypeScript file.

# Specify the correct path when importing the JSON file

And here is how we import the JSON file into an index.ts file.

index.ts

Copied!

import employee from './employee.json';// 👇️ "BOBBY HADZ"console.log(employee.name.toUpperCase());// 👇️ [2022, 2023, 2024]console.log(employee.years);

How to Import a JSON file in TypeScript | bobbyhadz (2)

The code for this article is available on GitHub

Make sure to correct the path to the employee.json file if you have to.

The example above assumes that the employee.json file and index.ts arelocated in the same directory.

For example, if your employee.json file was one directory up, you would importit as import employee from '../employee.json'.

# Set moduleResolution to node in your tsconfig.json file

If you get an error, try setting moduleResolution to node in yourtsconfig.json file.

tsconfig.json

Copied!

{ "compilerOptions": { // ... other settings "moduleResolution": "node", "esModuleInterop": true, "resolveJsonModule": true }}

You should also make sure that the JSON file you are importing is located underyour rootDir.

For example, the rootDir setting in my tsconfig.json is set to src. Therefore the json file I am importing has to be located under the src directory.

If your json file is not under your rootDir, you will get an error: "Fileis not under 'rootDir'. 'rootDir' is expected to contain all source files.".

If you are still unable to import the JSON file, try importing it as follows.

index.ts

Copied!

import * as employee from './employee.json';// 👇️ "BOBBY HADZ"console.log(employee.name.toUpperCase());// 👇️ [2022, 2023, 2024]console.log(employee.years);

TheesModuleInteropoption is set to false by default, which causes it to treat CommonJS modulessimilar to ES6 modules. This causes some issues.

Setting esModuleInterop to true fixes these issues.

TheresolveJSONModuleoption allows us to import modules with .json extension in our TypeScriptfiles.

# The JSON import is automatically typed correctly

The resolveJSONModule option is set to false by default, so make sure to setit to true in your tsconfig.json file.

If the option is set to false, you will get an error - "Cannot find module'./employee.json'. Consider using '--resolveJsonModule' to import module with'.json' extension.ts(2732)".

This setting also generates a type for the import based on the static JSON shape and enables autocomplete in your IDE.

How to Import a JSON file in TypeScript | bobbyhadz (3)

The rootDir option points tothe longest common path of all non-declaration input files.

The setting enforces that all files that need to be emitted are under therootDir path. Therefore your .json file has to be under the specifiedrootDir for the import to work.

I've also written a detailed guide onhow to import values from another file in TS.

# Specifying different types for the import JSON file

If you need to specify different types for the imported JSON object, use a typeassertion.

index.ts

Copied!

import emp from './employee.json';type Employee = { id: number; name: string; salary: number; years: number[];};const employee = emp as Employee;console.log(employee.id);console.log(employee.name);console.log(employee.salary);console.log(employee.years);

The code for this article is available on GitHub

Type assertionsare used when we have information about the type of a value that TypeScriptcan't know about.

The employee variable is now of type Employee, so we can access allproperties an Employee has on the variable.

# Additional Resources

You can learn more about the related topics by checking out the followingtutorials:

How to Import a JSON file in TypeScript | bobbyhadz (2024)
Top Articles
How to find servers name or address of VPN?
The Added Benefits of Military Service | Military OneSource
Euro (EUR), aktuální kurzy měn
How Many Cc's Is A 96 Cubic Inch Engine
Apex Rank Leaderboard
Notary Ups Hours
Noaa Swell Forecast
Paula Deen Italian Cream Cake
Top Hat Trailer Wiring Diagram
Guardians Of The Galaxy Vol 3 Full Movie 123Movies
Shooting Games Multiplayer Unblocked
My.doculivery.com/Crowncork
Diablo 3 Metascore
Uhcs Patient Wallet
Busted Newspaper S Randolph County Dirt The Press As Pawns
U/Apprenhensive_You8924
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Colorado mayor, police respond to Trump's claims that Venezuelan gang is 'taking over'
Walmart Double Point Days 2022
My.tcctrack
Arre St Wv Srj
Weather Rotterdam - Detailed bulletin - Free 15-day Marine forecasts - METEO CONSULT MARINE
Ukc Message Board
Welcome to GradeBook
Moving Sales Craigslist
Halo Worth Animal Jam
Juicy Deal D-Art
Miltank Gamepress
Wsbtv Fish And Game Report
Sessional Dates U Of T
Synergy Grand Rapids Public Schools
Nearest Ups Ground Drop Off
Tottenham Blog Aggregator
Shia Prayer Times Houston
Mastering Serpentine Belt Replacement: A Step-by-Step Guide | The Motor Guy
Persona 4 Golden Taotie Fusion Calculator
Indiana Immediate Care.webpay.md
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Cross-Border Share Swaps Made Easier Through Amendments to India’s Foreign Exchange Regulations - Transatlantic Law International
Radical Red Doc
Delaware judge sets Twitter, Elon Musk trial for October
A Comprehensive 360 Training Review (2021) — How Good Is It?
Gt500 Forums
Riverton Wyoming Craigslist
Sdn Fertitta 2024
COVID-19/Coronavirus Assistance Programs | FindHelp.org
Craigslist Central Il
Poe Self Chill
Interminable Rooms
Hampton In And Suites Near Me
18443168434
4015 Ballinger Rd Martinsville In 46151
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6118

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.