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?
modules.d.ts
toinclude
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 json – Hiddenitesrc
is ininclude
intsconfig.json
. Code: gist.github.com/gknapp/22dd80ecd3a29e685e4b43d2fed2874d – Dormitory