Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Typed JSON imports with import attributes

Give TypeScript the shape of a JSON settings file and use import attributes to load it in a Node ES module.

Your Node script reads a checked-in settings file and reaches for settings.retires. The typo would be easy to catch in a TypeScript object. Give TypeScript the JSON file as a module and it can catch the same typo in the import.

Let TypeScript read the file

Use TypeScript 5.7 or later and Node 22.12 or later on the Node 22 release line. Add this tsconfig.json. This example uses a .mts entry point so TypeScript treats it as an ES module even without a type field in package.json.

{
  "compilerOptions": {
    "module": "nodenext",
    "resolveJsonModule": true,
    "strict": true,
    "outDir": "dist"
  },
  "include": ["report.mts"]
}

With that config, the compiler resolves JSON imports and uses the file’s shape to assign a type. See TypeScript’s JSON module setting.

Save this beside tsconfig.json as settings.json.

{
  "region": "eu-west",
  "retries": 3
}

TypeScript can now infer a string property called region and a number property called retries from that file.

Give Node its import attribute

Use a default import in report.mts, with type: "json" in the import attributes. Node uses the attribute to load the module. TypeScript 5.7 added the check for this attribute under nodenext. See the JSON import validation release notes.

import settings from './settings.json' with { type: 'json' }

console.log(settings.region.toUpperCase(), settings.retries + 1)

Run pnpm exec tsc, then node dist/report.mjs. You see EU-WEST 4.

Change settings.retries to settings.retires and run the compiler again. It reports that the property does not exist and suggests retries. Change the JSON value to "3" instead and TypeScript sees a string. The result becomes EU-WEST 31 because + concatenates the string. Assign settings.retries to a number-annotated variable to make a string in the JSON a compile-time error.

Read the error at the right layer

An error saying the JSON module cannot be found can mean the file path is wrong or your command picked up another tsconfig. Run pnpm exec tsc -p tsconfig.json from the directory with the config and verify the spelling of the import. The file needs to be present in the output directory beside report.mjs when you deploy.

If the compiler complains about a missing JSON import attribute under nodenext, put back the with clause. For the runtime behaviour behind that clause, see how Node loads JSON modules. Use this pattern for JSON you ship with the code. A JSON response that arrives while the program runs needs its own validation.