TypeScript の as constアサーション
レベル 3305 打鍵
as constアサーションは値をreadonlyにし、型を広げずにリテラル型のまま保ちます。
TypeScript のコード
// 型はstring[]ではなくreadonly ["red", "green", "blue"]1const colors = ["red", "green", "blue"] as const;// numberで添字を取ると"red" | "green" | "blue"になる2type Color = typeof colors[number];// as constにより、各値は"/about"のようなリテラル型のまま3const routes = {4 home: "/",5 about: "/about",6 contact: "/contact"// as constはすべてのプロパティもreadonlyにする7} as const;// すべての値のユニオン:"/" | "/about" | "/contact"8type Route = typeof routes[keyof typeof routes];// 3色のどれかでなければならない9const myColor: Color = "red";// 3つのルートのどれかでなければならない10const myRoute: Route = "/about";// 「red /about」を表示する11console.log(myColor, myRoute);実行結果
red /about
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
"× 16;× 7=× 6,× 5:× 5/× 4[× 3]× 3.× 1(× 1