Skip to content

Instantly share code, notes, and snippets.

@jcreedcmu
Created January 1, 2019 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcreedcmu/62ad0d35dc19a4514a6be48bc94572e7 to your computer and use it in GitHub Desktop.
Save jcreedcmu/62ad0d35dc19a4514a6be48bc94572e7 to your computer and use it in GitHub Desktop.
b.ts
type Lang = 'en' | 'es';
type Intl<T> = {
forms: { new_form: T },
hello: T
};
type Dict<T extends string, U> = { [k in T]: U };
type LangDataIn = Dict<Lang, Intl<string>>;
type LangDataOut = Intl<Dict<Lang, string>>;
const all_langs: LangDataIn = {
en: { forms: { new_form: "New Form" }, hello: 'hello' },
es: { forms: { new_form: "Nuevo Formo" }, hello: 'hola' },
}
// Does some 'unsafe' things internally, but should satisfy this type spec.
function mapValues<T extends string, U, V>(ob: Dict<T, U>, f: (x: U) => V): Dict<T, V> {
const rv: Dict<T, V> = {} as Dict<T, V>;
Object.keys(ob).forEach(k => rv[k as T] = f(ob[k as T]));
return rv;
}
function cvt(langs: LangDataIn): LangDataOut {
return {
forms: { new_form: mapValues(langs, l => l.forms.new_form) },
hello: mapValues(langs, l => l.hello)
};
}
console.log(JSON.stringify(cvt(all_langs), null, 2));
/*
{
"forms": {
"new_form": {
"en": "New Form",
"es": "Nuevo Formo"
}
},
"hello": {
"en": "hello",
"es": "hola"
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment