0

Is there a way to import a JSON object into a Typescript program so that it is automatically strongly typed and constant?

So if I have this code in person.json:

{
  "name": "Steven",
  "eyeColor": "brown"
}

I want to be able to import it to a Typescript program as such:

// personTest.ts
const person = require('person.json');
console.log(person.name); // This should be fine
console.log(person.age);  // This should cause a compile-time error, because this property is not defined
1
  • 1
    have you tried using ESM ? import person from 'person.json' Commented Mar 18, 2022 at 21:45

1 Answer 1

3

add this on tsconfig.json

{

   ... //prev code

   "resolveJsonModule": true, 

}

then you can use ESM modules to import json file and it will be auto typed the object values

import person from './person.json' //be sure from the json path
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.