Skip to content

Commit

Permalink
feat: add assertion helper functions
Browse files Browse the repository at this point in the history
Functions to help with checking if a string is actually a `LocaleCode`
  • Loading branch information
SimeonC committed Jul 31, 2024
1 parent 5671ea3 commit 4012645
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4012645

Please sign in to comment.