Change the type of an imported JSON in TypeScript
Asked Answered
X

1

11

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?

Xenomorphic answered 26/9, 2020 at 12:55 Comment(2)
Did add modules.d.ts to include in your tsconfig? Do it, if not, because if you didn't, typescript will not see this file, because you do not import it explicitly. Also you could write ///<reference path="path/to/modules.d.ts" /> in the beginning of this second file where you import jsonHiddenite
I tried something similar but no joy. I wanted to reference an interface I am already using elsewhere in my app. src is in include in tsconfig.json. Code: gist.github.com/gknapp/22dd80ecd3a29e685e4b43d2fed2874dDormitory
W
-4

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
      }
   }
}
Wei answered 11/9, 2022 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.