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 string1const 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 kompilieren9function navigate(path: RouteValues): void {10 console.log(`Navigating to: ${path}`);11}// Ein Array mit as const wird zu einem readonly-Tupel12const tuple = [1, "hello", true] as const;// Ergibt readonly [1, "hello", true] (TupleType wird zur Laufzeit nicht verwendet)13type TupleType = typeof tuple;// Gibt "Navigating to: /" aus14navigate(routes.home);// Gibt "Navigating to: /about" aus15navigate(routes.about);// Gibt "Tuple: 1, hello, true" aus16console.log(`Tuple: ${tuple.join(", ")}`);Ausgabe
Navigating to: / Navigating to: /about Tuple: 1, hello, true
Ü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