as-const-Assertion in TypeScript
Level 3305 Tastenanschläge
Die Assertion as const macht Werte readonly und behält ihre Literaltypen, statt sie zu verbreitern.
TypeScript-Code
// Der Typ ist readonly ["red", "green", "blue"], nicht string[]1const colors = ["red", "green", "blue"] as const;// Indizieren mit number ergibt "red" | "green" | "blue"2type Color = typeof colors[number];// Mit as const behält jeder Wert seinen Literaltyp, z. B. "/about"3const routes = {4 home: "/",5 about: "/about",6 contact: "/contact"// as const macht außerdem alle Eigenschaften readonly7} as const;// Union aller Werte: "/" | "/about" | "/contact"8type Route = typeof routes[keyof typeof routes];// Muss eine der drei Farben sein9const myColor: Color = "red";// Muss eine der drei Routen sein10const myRoute: Route = "/about";// Gibt "red /about" aus11console.log(myColor, myRoute);Ausgabe
red /about
Ü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.
"× 16;× 7=× 6,× 5:× 5/× 4[× 3]× 3.× 1(× 1