By setting resolveJsonModule
in your tsconfig
to true, TypeScript will attempt to get the type/shape of the JSON for you.
We can use this to provide better type safety and auto complete for functions that use the JSON files.
For example typing i18n/resource. Either for custom solutions, library wrappers, or for libraries themselves.
Using existing/static imports.
Static imports are the usual imports you see at the top of the file.
If we are already statically importing our JSON resource, we can use typeof
& keyof
to get its type and keys.
import Resources from './resource.json';
type ResourceKeys = keyof typeof Resources;
// Index to keys path if complex.
// type ResourceKeys = keyof typeof Resources['path']['to']['key']
...
function translate(key: ResourceKeys): string { ... }
Using Dynacmic Imports
If we are worried about the import cost, then we can use dynamic imports for our actual code & type imports for the TypeScript types.
// Type only import.
// Stripped when transpiled
import type Resources from './resource.json';
type ResourceKeys = keyof typeof Resources;
async function connect(...) {
// Dynamic import
const resource = await import ('./resource.json');
...
}
...
function translate(key: ResourceKeys): string { ... }
If your version of TypeScript does not support typed imports, then we can extract out the types to separate file.
// ResourceTypes.ts
/*
Import is only used for type (no JS code).
This file only contains types.
> Will get transpiled to an empty file
> Will be tree shaken out of bundle.
*/
import Resources from './resource.json'
export type ResourceKeys = keyof typeof Resources
Using Declaration Files
Finally we could modify/use declaration files. This is great if you are using a library E.g. i18next docs.
Conclusion
We have successfully used this to provide auto-complete & type safety. We have even spotted missing or misspelled keys!
One caveat is that we had to restart our TS server if our resources were modified or new keys were added. I think this was due to our large resources, or maybe due to caching done on the TS server?
But a relatively small price to get this type safety.
Top comments (0)