summaryrefslogtreecommitdiff
path: root/src/i18n/translate.ts
blob: 0366798569005eb6be9c46c44074cb7bbe47705a (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
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: TranslationsDictionaryWith<Key, ParamsHash>,
    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);
  };
}