Change the type of an imported JSON in TypeScript

Viewed 1327

When importing a JSON file in a TypeScript project with the resolveJsonModule option enabled the TypeScript compiler is able to automatically infer the type of the imported JSON file. However, this type is too specific and I want to replace it with a more generic one. I tried to do this by writing a custom type definitions file:

// file modules.d.ts

declare module "*.json" {
  const value: Record<string, string>;
  export default value;
}

but the TypeScript compiler ignores this definition.

The only way that works for me is to use temporary variables, like this:

import DATA_JSON from "./data.json";

const DATA  = DATA_JSON as Record<string, string>; // Use my own type instead of the inferred one.

export { DATA };

but this is boring. Is there any other way to give my own types to JSON files imported in TypeScript?

1 Answers

you could try it with mapped types. Not sure what structure/types you want to achieve but I believe it's the way to go.

Having such requirement sounds like a good moment to start exploring advanced TS (I recommend Matt Pocock on yt)

import DATA_JSON from './data.json';

const OWN_TYPED_DATA_JSON = DATA_JSON as unknown as {
   [key in keyof typeof DATA_JSON]: {
      [nestedKey in keyof typeof DATA_JSON[key]]: {
         [moreNestedKey in keyof typeof DATA_JSON[key][nestedKey]]: string
      }
   }
}
Related