TypeScript Reference ยท tsconfig: Language, Modules and Emit Options
TypeScript resolveJsonModule option
Reference for resolveJsonModule: importing .json files with inferred types, import attributes under nodenext, what gets emitted and the common pitfalls.
resolveJsonModule lets TypeScript treat a .json file as a module. You import it like any other file, and the compiler infers a type from the content, so config.port is a number and a typo such as config.prot is an error.
Set the option explicitly in projects that read JSON, because the default depends on the module settings. Under module: nodenext a JSON import must also carry an import attribute, with { type: "json" }, and only a default import is allowed, matching what Node does at run time.
import config from "./config.json" with { type: "json" }; console.log(config.port);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
{ "compilerOptions": { "resolveJsonModule": true } }
| Part | Description |
|---|---|
| Value | true or false. Set it explicitly; the default depends on module and moduleResolution. |
| Import form | import data from "./data.json" (add with { type: "json" } under nodenext). |
| Inferred type | The shape of the file, with string, number and boolean instead of literal types; arrays become T[]. |
| Emit | The JSON file is copied to outDir and must be matched by include. |
Edge cases: an array at the top level or a very large file is typed in full, which can slow the editor. import data from is fine, but import { port } from "./config.json" is not allowed under nodenext.
Usage notes
- Add the file to the project. A
.jsonfile is only part of the build ifincludematches it, for example"include": ["src/**/*", "src/**/*.json"]. - No literal types. If you need
"production" | "development", cast through a typed variable or validate the value at runtime; do not expect the compiler to know the literal. - Import attributes under Node. Node requires
with { type: "json" }; leaving it off is a type error undernodenextand a runtime error in Node. - Not for secrets or user-editable config. Imported JSON is bundled or read at start-up. Use environment variables or a loader for values that change per deployment.
- Untrusted JSON is still
unknown. Types from this option describe the file in your repository, not data that arrives later; see Importing JSON. package.jsonimports work the same way, which is handy for readingversion.