Adding a type definition for a JSON file in typescript

Viewed 2253

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

2 Answers

Typescript will not validate your json. It only works in .ts and .tsx files.

What your d.ts there will do is assume that the data imported from config.json conforms to your type, but it will not actually ensure that since json files are outside of typescript's domain.

A workaround would be to put this config in a config.ts file instead with something like:

// config.ts
export default {
  //...
} as MyDataFormat
Related