summaryrefslogtreecommitdiff
path: root/src/i18n/translate.ts
blob: 09e227c0a90f69d1aebc37c5348fbffc688f15d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type Locale from '$types/Locale';
import type {
  TranslationsDictionary,
  Translation,
  LocalesTranslationHash,
} from '$types/TranslationsDictionary';
import { defaultLocale } from './locales';

type TranslationsDictionaryWith<
  Key extends string | number,
  ParamsHash extends object,
> = TranslationsDictionary<{
  [key in Key]: LocalesTranslationHash<ParamsHash>;
}>;

export default function (locale: Locale) {
  return function <
    Key extends string | number,
    ParamsHash extends object,
    Dict extends TranslationsDictionaryWith<Key, ParamsHash>,
  >(dict: Dict, params: { key: Key } & ParamsHash) {
    if (!(params.key in dict)) {
      throw new Error(`
        Could not find translation for key '${params.key}'. Available keys were:
        ${Object.keys(dict)
          .map((k) => `'${k}'`)
          .join(', ')}
      `);
    }
    const localesTranslationHash: LocalesTranslationHash<ParamsHash> = dict[params.key];
    const translation: Translation<ParamsHash> =
      localesTranslationHash[locale] ?? localesTranslationHash[defaultLocale];
    return translation(params);
  };
}