Created
February 21, 2020 12:48
-
-
Save colelawrence/a928845d7468840dac9bf80668077f27 to your computer and use it in GitHub Desktop.
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 LanguageKey = keyof Definitions<any> | |
let currentLanguage: LanguageKey = "en" | |
/** | |
* @param namespace most underlying i18n solutions like to have a namespace | |
*/ | |
function define<T>(namespace: string, definitions: Definitions<T>): Translate<T> { | |
// ... set up with your existing translation library which supports fallbacks and such... | |
return key => `Key (${key}) has no definition` | |
} | |
type Translate<T> = (key: keyof T, params?: any) => string | |
/** development type */ | |
type Definitions<T> = { | |
en: T, | |
fr: Partial<T>, | |
} | |
// greeting.i18n.ts | |
// separate your translation files based on part of the product being worked on | |
const greetingI18n = define('greeting', { | |
en: { | |
// depending on the way your translation lib works, you could use functions and template strings here, too. | |
hello$name: "Hello, $name!", | |
// many libraries use key suffixes to mean special things | |
cartItems$count: "one item", | |
cartItems$count_2: "two items", | |
cartItems$count_plural: "$count items", | |
}, | |
fr: { | |
hello$name: "Bonjour, $name!", | |
cartItems$count: "un article", | |
cartItems$count_2: "deux articles", | |
cartItems$count_plural: "$count articles", | |
} | |
}) | |
// see how the first argument can be autocompleted | |
// then, the key itself ("cartItems$count") describes the parameters | |
// we're expecting. Although not "type-checked", it is simpler, very compatible, | |
// and gets us 90% of the way there (as far as defining expectations) | |
console.log(greetingI18n("cartItems$count", { count: 2 })) |
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
https://www.typescriptlang.org/play/#code/C4TwDgpgBAMghgOwOYFc5IgaQiKBeKAaxwHsAzKAEQjIEsFbhaSEBnAHkRAD4AoXgDYRgUAMYoAThIgJg8ZGgwAuWIlTosOfFABEMnfwD0AKmO8oxqAAEwcCXAC2UBI4itbo6A5KsRKBAAmEBICIPRIULQAjAAcCFCsJAIoTCysUAK0xFDA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