How to reference a JSON file in TypeScript? How to reference a JSON file in TypeScript? json json

How to reference a JSON file in TypeScript?


Since you have the contents of the JSON file loaded into the string already, you must just remember to set the Content-Type header on the response to application/json. This is what indicates to the client what the type of the response body is. Assuming you are using express, you just need to add res.setHeader('Content-Type', 'application/json'); before your call to res.send.


Within nodejs if a JSON file is simply imported then it will automatically be parsed into an object:

const keyFile = require('./keyfile.json');

Update: If you are using TS >=2.9:

Support for well-typed JSON imports TypeScript is now able to import JSON files as input files when using the node strategy for moduleResolution. This means you can use json files as part of their project, and they’ll be well-typed!

// ./tsconfig.json{    "compilerOptions": {        "module": "commonjs",        "resolveJsonModule": true,        "esModuleInterop": true        "outDir": "lib"    },    "include": ["src"]}// ./src/settings.json{    "dry": false,    "debug": false}// ./src/foo.tsimport settings from "./settings.json";settings.debug === true;  // Okaysettings.dry === 2;       // Error! Can't compare a `boolean` and `number`

These JSON files will also carry over to your output directory so that things “just work” at runtime.