diff --git a/src/index.ts b/src/index.ts index f0e98517903..a42aa7987d2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { Hacker } from './hacker'; import { Helpers } from './helpers'; import { Image } from './image'; import { Internet } from './internet'; +import type { KnownLocale } from './locales'; import allLocales from './locales'; import { Lorem } from './lorem'; import { Mersenne } from './mersenne'; @@ -25,6 +26,9 @@ import { Unique } from './unique'; import { Vehicle } from './vehicle'; import { Word } from './word'; +// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-471566609 +type LiteralUnion = T | (U & { zz_IGNORE_ME?: never }); + export interface LocaleDefinition { title: string; separator?: string; @@ -186,12 +190,13 @@ export interface LocaleDefinition { [group: string]: any; } +export type UsableLocale = LiteralUnion; +export type UsedLocales = Partial>; + export interface FakerOptions { - locales?: { - [locale: string]: LocaleDefinition; - }; - locale?: string; - localeFallback?: string; + locales?: UsedLocales; + locale?: UsableLocale; + localeFallback?: UsableLocale; } export interface DefinitionTypes { @@ -216,11 +221,9 @@ export interface DefinitionTypes { } export class Faker { - locales: { - [locale: string]: LocaleDefinition; - }; - locale: string; - localeFallback: string; + locales: UsedLocales; + locale: UsableLocale; + localeFallback: UsableLocale; // TODO @Shinigami92 2022-01-11: For now we loose types here // @ts-expect-error: will be lazy filled by constructor @@ -432,7 +435,7 @@ export class Faker { * * @param locale */ - setLocale(locale: string): void { + setLocale(locale: UsableLocale): void { this.locale = locale; } } diff --git a/src/locales/index.ts b/src/locales/index.ts index 43cd2ee067e..83c012f7118 100644 --- a/src/locales/index.ts +++ b/src/locales/index.ts @@ -56,7 +56,67 @@ import zh_CN from './zh_CN'; import zh_TW from './zh_TW'; import zu_ZA from './zu_ZA'; -const locales: { [lang: string]: LocaleDefinition } = { +export type KnownLocale = + | 'af_ZA' + | 'ar' + | 'az' + | 'cz' + | 'de' + | 'de_AT' + | 'de_CH' + | 'el' + | 'en' + | 'en_AU' + | 'en_AU_ocker' + | 'en_BORK' + | 'en_CA' + | 'en_GB' + | 'en_GH' + | 'en_IE' + | 'en_IND' + | 'en_NG' + | 'en_US' + | 'en_ZA' + | 'es' + | 'es_MX' + | 'fa' + | 'fi' + | 'fr' + | 'fr_BE' + | 'fr_CA' + | 'fr_CH' + | 'ge' + | 'he' + | 'hr' + | 'hy' + | 'id_ID' + | 'it' + | 'ja' + | 'ko' + | 'lv' + | 'mk' + | 'nb_NO' + | 'ne' + | 'nl' + | 'nl_BE' + | 'pl' + | 'pt_BR' + | 'pt_PT' + | 'ro' + | 'ru' + | 'sk' + | 'sv' + | 'tr' + | 'uk' + | 'ur' + | 'vi' + | 'zh_CN' + | 'zh_TW' + | 'zu_ZA'; + +export type KnownLocales = Record; + +const locales: KnownLocales = { af_ZA, ar, az,