Issue
I want to create file factory (e. g. JSON with translations in my case).
{
"field": "",
"group": {
"field_1": "",
"field_2": ""
},
...
}
I wish to create a template JSON with all fields that are present in my translations, and then instantiate it with some default values for each locale to allow my application not to miss any translation fields. Well, that is pretty simple, at output I have couple of files (based on count of locales), named <locale>.json
, e.g. en.json
with some content like this:
{
"field": "en:field",
"group": {
"field_1": "en:group.field_1",
"field_2": "en:group.field_2",
},
...
}
Now I want to create a type or interface based on my JSON template to allow my translation fields to be displayed in quick suggests of my IDE (e.g. VS Code).
Is there any possibilities to do this in convenient way? I know that I can dynamically create a .ts
file with exported interface, but this is not so good because all ts
syntax will be provided through string, so there could be some mistakes during creation. May be there is any legal ways?
To be clear, I want to get an interface like this
interface IMyCoolInterface {
field: string,
group: {
field_1: string,
field_2: string,
},
...
}
Solution
You could use the --resolveJsonModule
compiler option introduced in TypeScript 2.9. Then you could import the template file as a module:
import * as translationTemplate from 'template.json';
and define a type for it using a typeof
type query:
type Translation = typeof translationTemplate;
If all goes well, if you declare a variable to be of type Translation
you should get IDE hints:
declare const t: Translation; // or whatever
t.field; // hinted at you
t.group.field_1; // likewise
Hope that helps. Good luck!
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.