How to strongly type your localization resource in TypeScript

Issue:

One common issue when we dealing with localization is, it is not easy to find out if a “string” is still being used. Often time we will do a global text search and try to see if anywhere still referencing it.

Solution:

What if we can strongly type our resource file. Then we can easily found out all the references. We will have error check during build time if a “string” is removed while still being used!

HowTo:

Let say we have a “resource.json” file holding localization string.

resource.json
-------------
{
“foo_bar”: “foo bar”
}

Create an .d.ts file right next to it.

resource.json.d.ts
------------------
interface Resource {
foo_bar: string;
}
declare const value: Resource;
export = value;

Now you should be able to use your resource file like below

import * as data from ‘./resource.json’;
let fooBarVal = data.foo_bar;

Advance:

If you have different language resource in different JSON files. With above instruction, we will have to create definition file per JSON file. But there is a way to avoid it.

Instead of creating definition file next to the JSON file. Update tsconfig.json, specify where do you want to load global typing by adding top level property “types”

“types”: [
“typePatches”
]

Under folder “typePatches”, create a d.ts file, e.g localizationResource.d.ts

interface Resource {
foo_bar: string;
}
declare module “*_resource.json” {
const val: Resource;
export = val;
}

Now rename our “resource.json” to something like “en_resource.json”