Deduce type from values

It is indeed possible to have a TypeScript type and an array of all of its
possible values without repeating ourselves.

The trick is - while we cannot go from types to values, we can go the other way
around. The sidetrick is - typeof array[number] gives us type of an array's
elements.

Combined, we get this pattern

    const fruits = ["banana", "orange"] as const;
    type Fruits = (typeof fruits)[number];

Refs:
- https://stackoverflow.com/questions/53154564/how-to-get-all-possible-values-of-a-union-type-to-an-array-or-the-other-way-aro
- https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html
This commit is contained in:
Manav Rathi 2024-02-23 10:23:37 +05:30
parent 1c2f7a4ba3
commit 85aaf1d27e

View file

@ -63,27 +63,20 @@ export const setupI18n = async (savedLocaleString?: string) => {
};
/**
* List of all {@link SupportedLocale}s.
*
* Locales are combinations of a language code, and an optional region code.
*
* For example, "en", "en-US", "en-IN" (Indian English), "pt" (Portuguese),
* "pt-BR" (Brazilian Portuguese).
*
* In our Crowdin Project, we have work-in-progress translations into quite a
* few languages. When a translation reaches a high enough coverage, say 90%,
* then we manually add it to this list of supported languages.
* In our Crowdin Project, we have work-in-progress translations into more
* languages than this. When a translation reaches a high enough coverage, say
* 90%, then we manually add it to this list of supported languages.
*/
export type SupportedLocale = "en" | "fr" | "zh" | "nl" | "es";
/**
* List of all {@link SupportedLocale}s.
*/
export const supportedLocales: SupportedLocale[] = [
"en",
"fr",
"zh",
"nl",
"es",
];
export const supportedLocales = ["en", "fr", "zh", "nl", "es"] as const;
/** The type of {@link supportedLocale}s. */
export type SupportedLocale = (typeof supportedLocales)[number];
/**
* Return the current locale in which our user interface is being shown.