Const-Assertions in TypeScript

Level 5420 Tastenanschläge

as const macht ein Objekt oder Array tief readonly und behält Literaltypen wie "/about" statt string. So akzeptiert navigate nur die tatsächlich vorhandenen Routenwerte.

TypeScript-Code

// Ohne as const hätte jeder Wert nur den Typ string
1const routes = {
2 home: "/",
3 about: "/about",
4 users: "/users"
// Macht die Eigenschaften readonly mit Literaltypen wie "/"
5} as const;
// Ergibt { readonly home: "/"; readonly about: "/about"; readonly users: "/users" }
6type Routes = typeof routes;
// Ergibt "home" | "about" | "users"
7type RouteKeys = keyof Routes;
// Ergibt "/" | "/about" | "/users"
8type RouteValues = Routes[RouteKeys];
// Nur vorhandene Pfade werden akzeptiert; navigate("/home") würde nicht kompilieren
9function navigate(path: RouteValues): void {
10 console.log(`Navigating to: ${path}`);
11}
// Ein Array mit as const wird zu einem readonly-Tupel
12const tuple = [1, "hello", true] as const;
// Ergibt readonly [1, "hello", true] (TupleType wird zur Laufzeit nicht verwendet)
13type TupleType = typeof tuple;
// Gibt "Navigating to: /" aus
14navigate(routes.home);
// Gibt "Navigating to: /about" aus
15navigate(routes.about);
// Gibt "Tuple: 1, hello, true" aus
16console.log(`Tuple: ${tuple.join(", ")}`);

Ausgabe

Navigating to: /
Navigating to: /about
Tuple: 1, hello, true
Diesen Code tippen üben

Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.

Symbole in diesem Code

Die Symbole, die du in diesem TypeScript-Code tippst, und wie oft sie vorkommen.

  • ;× 10
  • "× 10
  • :× 7
  • (× 6
  • )× 6
  • =× 6
  • ,× 5
  • .× 5
  • {× 4
  • }× 4

Weitere TypeScript-Beispiele auf Level 5

← TypeScript-Tippübungen