summaryrefslogtreecommitdiff
path: root/src/i18n/translate.ts
blob: a9415b2f9ef62394e2a7a7c512ab05a00551ab72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import type Locale from '$types/Locale';
import type { TranslationsDictionary, Translation } from '$types/TranslationsDictionary';
import { defaultLocale } from './locales';

type TranslationsDictionaryWith<Key extends string, Params> = TranslationsDictionary<{
  [key in Key]: { [locale in typeof defaultLocale]: Translation<Params> } & {
    [locale in Locale]?: Translation<Params>;
  };
}>;

export default function (locale: Locale) {
  return function <
    Key extends string,
    Params,
    Dict extends TranslationsDictionaryWith<Key, Params>,
  >(dict: Dict, params: { key: Key } & { [Param in keyof Params]: string }) {
    const translation = dict[params.key][locale] ?? dict[params.key][defaultLocale];
    return translation(params);
  };
}