Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a type definition for a JSON file in typescript

I have a configuration file config.json that lives in my typescript project that I want to add strong typing for.

src/config.json

{
   "id": "some-id-string",
   "data": { 
     "somekey" : "some value"
  }
}

In order to add the typing, I added an index.d.ts file to my project as well:

src/index.d.ts

declare module 'config.json' {
  export const id: string;
  export const data: Record<string, string>;
}

However it doesn't seem to work, as I can add arbitrary fields to my config.json and typescript is happy to let them through, ie:

src/config.json

{
   "id": "some-id-string",
   "foo": "bar", // <-- typescript doesn't catch this
   "data": { 
     "somekey" : "some value"
  }
}

I've created this project using create-react-app with the typescript flag, which produces the following tsconfig.json:

tsconfig.json


{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"]
}

I think I'm missing some small step here, but I'm not sure and I couldn't find many examples of how this is done.

EDIT: It seems like this is doable, given that the tsconfig.json itself has strong typing:

strongly typed json

like image 777
Danny Delott Avatar asked Oct 25 '25 01:10

Danny Delott


1 Answers

The "strong typing" provided in the tsconfig.json file is not actually the work of TypeScript at all!

Instead, VSCode is using a built-in JSONSchema integration to provide type hints for json files. https://code.visualstudio.com/docs/languages/json

Many open-source libraries provide JSON schemas for there configs, eg: webpack, eslint, etc.. (https://schemastore.azurewebsites.net/json/)

like image 73
Danny Delott Avatar answered Oct 26 '25 16:10

Danny Delott