From 4012645be952546ed26b58324ca0f6c4abe9bfbc Mon Sep 17 00:00:00 2001 From: SimeonC <1085899+SimeonC@users.noreply.github.com> Date: Wed, 31 Jul 2024 11:08:25 +0900 Subject: [PATCH] feat: add assertion helper functions Functions to help with checking if a string is actually a `LocaleCode` --- src/index.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/index.ts b/src/index.ts index 94759a2..64bb52e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -105,6 +105,46 @@ export function orderLocales(localesToOrder: LooseLocaleCode[]): LocaleCode[] { // eslint-disable-next-line @typescript-eslint/ban-types -- this supports autocomplete of only LocaleCode values but is typed as string type LooseLocaleCode = LocaleCode | (string & {}); +/** + * Check if the string is a valid `LocaleCode` + * @param locale + * @returns true if the locale is a valid `LocaleCode` + * + * @example + * + * ```ts + * const locale: string = 'en'; + * if (isLocaleCode(locale)) { + * const typedLocale: LocaleCode = locale; // no error + * } + * const typedLocale2: LocaleCode = locale; // error as locale is string + * ``` + */ +export function isLocaleCode(locale: LooseLocaleCode): locale is LocaleCode { + return orderedLocaleCodes.includes(locale as LocaleCode); +} + +/** + * Use this function to assert that a `string` is a valid `LocaleCode` + * @param locale + * @throws Error if the locale is not a valid `LocaleCode` + * + * @example + * + * ```ts + * const locale: string = 'en'; + * assertLocaleCode(locale); + * const typedLocale: LocaleCode = locale; // no error as locale is now LocaleCode typed + * ``` + */ +export function assertLocaleCode( + locale: LooseLocaleCode +): asserts locale is LocaleCode { + if (!orderedLocaleCodes.includes(locale as LocaleCode)) { + throw new Error(`Invalid Locale Code: ${locale}`); + } +} + /** * Function to check if a locale is CJK - Chinese/Japanese/Korean. * Often logic is set to be different in these three language types as they