typescriptvitesveltekit

How to type the import from a json file?


The import itself works fine

import json from '$lib/example.json'

What I found and tried is adding this

declare module '*.json' {
    const value: MyType[];
    export default value;
}

to app.d.ts but the type is still inferred from the data


Solution

  • One thing that appears to work is adding a query string to the import, e.g.

    // json.d.ts
    declare module '*.json?my-type' {
      const value: MyType[];
      export default value;
    }
    
    import json from '$lib/example.json?my-type';
    

    (If the type declaration file is using an import for the type, the file becomes a module and requires that the declaration is wrapped in a declare global block to apply everywhere.)