Quellcode durchsuchen

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
Manav Rathi vor 1 Jahr
Ursprung
Commit
85aaf1d27e
1 geänderte Dateien mit 8 neuen und 15 gelöschten Zeilen
  1. 8 15
      packages/ui/i18n.ts

+ 8 - 15
packages/ui/i18n.ts

@@ -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.
- */
-export type SupportedLocale = "en" | "fr" | "zh" | "nl" | "es";
-
-/**
- * List of all {@link SupportedLocale}s.
+ * 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 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.