-
-
Save jcreedcmu/62ad0d35dc19a4514a6be48bc94572e7 to your computer and use it in GitHub Desktop.
b.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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